Notice
Recent Posts
Recent Comments
Link
천리길도 한걸음부터
문제07 방문 길이⭐⭐ 본문
- 저자 권장 시간 : 40분
- 권장 시간 복잡도 : O(N)
- 출제 : Summer/Winter Coding(~2018)
import java.util.HashMap;
import java.util.HashSet;
class Solution {
// 1. 좌표평면을 벗어나는지 체크하는 메서드
private static boolean isValidMove(int nx, int ny) {
return 0 <= nx && nx < 11 && 0 <= ny && ny < 11;
}
// 2. 다음 좌표 결정을 위한 해시맵 생성
private static final HashMap<Character, int[]> location = new HashMap<>();
private static void initLocation() {
location.put('U', new int[]{0, 1});
location.put('D', new int[]{0. -1});
location.put('L', new int[]{-1, 0});
location.put('R', new int[]{0, 1});
}
public int solution(String dirs) {
initLocation();
int x = 5, y = 5;
HashSet<String> answer = new HashSet<>(); // 3. 겹치는 좌표는 1개로 처리하기 위함
// 4. 주어진 명령어로 움직이면서 좌표 지정
for (int i=0; i<dirs.length; i++) {
int[] offset = location.get(dirs.charAt(i))
int nx = x + offset[0];
int ny = y + offset[1];
if (!isValidMove(nx, ny)) // 5. 벗어난 좌표는 인정하지 않음
continue;
// 6. A에서 B로 간 경우 B에서 A로 추가해야 함(총 경로의 개수는 방향성이 없음)
answer.add(x + " " + y + " " + nx + " " + ny);
answer.add(nx + " " + ny + " " + x + " " + y);
// 7. 좌표를 이동했으므로 업데이트
x = nx;
y = ny;
}
return answer.size()/2;
}
}
여기까지가 배열 끝이다..
해시맵, 해시셋 등 기본 자료형들 선언, 값 입출력 하는 법 익히고,
반복문과 함께 사용하는 경우 익히고,...
그... stream 화해서 Integer로 형변환? 하는 것은 외워야 할듯;;
'코딩 테스트 합격자 되기_자바💜' 카테고리의 다른 글
문제09 10진수를 2진수로 변환하기⭐ (0) | 2024.08.15 |
---|---|
문제08 올바른 괄호⭐⭐ (0) | 2024.08.15 |
문제06. 실패율⭐⭐ (0) | 2024.08.12 |
문제05. 행렬의 곱셈⭐ (0) | 2024.08.10 |
문제04. 모의고사⭐ (0) | 2024.08.08 |