


가로 세로로 배열을 나누어, 방문한적이 있는지 검사하는 방식으로 문제를 해결했다.


import java.util.*;
class Solution {
public int solution(String dirs) {
int answer = 0;
boolean[][] garo = new boolean[11][10]; // 가로 방향의 길을 저장
boolean[][] sero = new boolean[10][11]; // 세로 방향의 길을 저장
int x = 0; // 현재 x좌표
int y = 0; // 현재 y좌표
for (char c : dirs.toCharArray()) {
if (c == 'U') {
if (y >= 5) continue; // 경계를 벗어나면 무시
y++;
if (!sero[5 - y][x + 5]) { // 처음 가는 길이면
answer++;
sero[5 - y][x + 5] = true; // 길 방문 표시
}
} else if (c == 'D') {
if (y <= -5) continue; // 경계를 벗어나면 무시
if (!sero[5 - y][x + 5]) { // 처음 가는 길이면
answer++;
sero[5 - y][x + 5] = true; // 길 방문 표시
}
y--;
} else if (c == 'R') {
if (x >= 5) continue; // 경계를 벗어나면 무시
if (!garo[5 - y][x + 5]) { // 처음 가는 길이면
answer++;
garo[5 - y][x + 5] = true; // 길 방문 표시
}
x++;
} else { // 'L'
if (x <= -5) continue; // 경계를 벗어나면 무시
x--;
if (!garo[5 - y][x + 5]) { // 처음 가는 길이면
answer++;
garo[5 - y][x + 5] = true; // 길 방문 표시
}
}
}
return answer;
}
}