- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/49993
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/방문 길이
풀이 시간 : 45분
import java.util.*;
class Solution {
public int solution(String dirs) {
Set<String> visited = new HashSet<>();
int x = 5, y = 5;
Map<Character, int[]> moves = Map.of(
'U', new int[]{0, 1}, 'D', new int[]{0, -1},
'L', new int[]{-1, 0}, 'R', new int[]{1, 0}
);
for (char dir : dirs.toCharArray()) {
int nx = x + moves.get(dir)[0];
int ny = y + moves.get(dir)[1];
if (nx < 0 || ny < 0 || nx > 10 || ny > 10) continue;
String path = x + "" + y + "" + nx + "" + ny;
String reversePath = nx + "" + ny + "" + x + "" + y;
if (!visited.contains(path)) {
visited.add(path);
visited.add(reversePath);
}
x = nx;
y = ny;
}
return visited.size() / 2; // 양방향
}
}