https://school.programmers.co.kr/learn/courses/30/lessons/49994
i, j 에서 x,y까지의 선에 접근한 적이 있는지를 판단을 어떻게 해야 하는가가 핵심 포인트였다
i,j 에서 U 방향으로 접근해 x, y에 도달하는 것과
x,y에서 U의 반대 방향인 D으로 접근해 i, j에 도달하는 것이 같기에
boolean[][][] visited = new boolean[N][M][4] 시작위치(i,j)에서 w 방향으로 간적이 있는가
위 배열을 둔다음에
정방향 역방향을 구해서 방문처리를 했다
import java.util.*;
class Solution {
static Map<Character, int[]> direction = new HashMap<>();
static boolean[][][] visited;
public int solution(String dirs) {
init();
int answer = 0;
// 처음 걸어본 길의 길이
// (i,j)에서 w방향
int x = 5, y = 5; // 양수
for(char d : dirs.toCharArray()) {
int[] dir = direction.get(d);
int nx = x + dir[0];
int ny = y + dir[1];
if(nx < 0 || nx >= 11 || ny < 0 || ny >= 11) continue;
// x,y에서 d방향 nx, ny에서 -d방향
if(!visited[x][y][dir[2]]){
visited[x][y][dir[2]] = true;
visited[nx][ny][(dir[2]+2)%4] = true;
answer += 1;
}
x = nx;
y = ny;
}
return answer;
}
void init() {
direction.put('U', new int[]{0,1, 0});
direction.put('L', new int[]{-1,0, 1});
direction.put('D', new int[]{0,-1 , 2});
direction.put('R', new int[]{1,0, 3});
visited = new boolean[11][11][4];// 0, 0 부터 10 ,10
}
}
[프로그래머스] [3차] 압축 (0) | 2025.02.04 |
---|---|
[백준] 14426: 접두사 (0) | 2025.02.03 |
[프로그래머스] 롤케이크 (0) | 2025.02.03 |
[프로그래머스] 프로세스 (0) | 2025.02.03 |
[프로그래머스] k진수에서 소수 개수 구하기 (0) | 2025.02.01 |