이번에 풀어본 문제는
프로그래머스 방문 길이 입니다.
class Solution {
public int solution(String dirs) {
int answer = 0;
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
boolean[][][][] isVisited = new boolean[11][11][11][11];
int x = 5, y = 5;
for (char dir: dirs.toCharArray()) {
int moveIdx = getIdxByChar(dir);
int mx = x + dx[moveIdx];
int my = y + dy[moveIdx];
if (isValid(mx, my)) {
if (!isVisited[x][y][mx][my]) {
isVisited[x][y][mx][my] = true;
isVisited[mx][my][x][y] = true;
answer++;
}
x = mx;
y = my;
}
}
return answer;
}
static int getIdxByChar(char c) {
switch (c) {
case 'U': return 0;
case 'D': return 1;
case 'L': return 2;
case 'R': return 3;
}
return 0;
}
static boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x <= 10 && y <= 10;
}
}
10*10 좌표에서 캐릭터가 이동할 때, 이미 이동한 길을 제외하고 몇 군데의 길을 거쳤는지를 반환하는 문제입니다.
좌표의 크기가 고정이고, 크지 않기 때문에 4차원 배열을 방문 배열로 활용했고, 각 좌표에서 좌표로 이동한 인덱스값을 방문배열에 기록하여 카운트해주었습니다.