Contents
내가 작성한 코드



내가 작성한 코드
import java.util.*;
class Solution {
public int solution(String dirs) {
Set<String> visited = new HashSet<>(); // 경로 저장 셋
// 현재위치
int x = 0;
int y = 0;
for (char dir : dirs.toCharArray()) {
// 이동할 위치
int nx = x;
int ny = y;
switch (dir) {
case 'U':
ny += 1;
break;
case 'D':
ny -= 1;
break;
case 'L':
nx -= 1;
break;
case 'R':
nx += 1;
break;
}
// 좌표 범위 검사
if (nx < -5 || nx > 5 || ny < -5 || ny > 5)
continue;
// 경로를 "작은 점 → 큰 점" 으로 정렬하여 저장
String path = x + "," + y + "-" + nx + "," + ny;
String reversePath = nx + "," + ny + "-" + x + "," + y;
visited.add(path);
visited.add(reversePath); // 양방향 모두 저장하여 중복 방지
// 위치 업데이트
x = nx;
y = ny;
}
// Set에 양방향 저장했으므로 /2
return visited.size() / 2;
}
}
Share article