ALGORITHM/PROGRAMMERS

[프로그래머스] 방문 길이

0298 2021. 8. 4. 22:40

https://programmers.co.kr/learn/courses/30/lessons/49994

 

코딩테스트 연습 - 방문 길이

 

programmers.co.kr

2021-08-04


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
    public static boolean[][][][] vtd;
    public static int solution(String dirs) {
        int answer = 0;
        vtd = new boolean[11][11][11][11];
        int x = 0;
        int y = 0;
         for(int i = 0; i < dirs.length(); i++) {
            char ch = dirs.charAt(i);
            int nx = x;
            int ny = y;
            switch (ch) {
                    case 'U':
                    if(ny + 1 <= 5) ny += 1;
                    else continue;
                    break;
                case 'L':
                    if(nx - 1 >= -5) nx -= 1;
                    else continue;
                    break;
                case 'D':
                    if(ny - 1 >= -5) ny -= 1;
                    else continue;
                    break;
                case 'R':
                    if(nx + 1 <= 5) nx += 1;
                    else continue;
                    break;
            }
            if (!vtd[nx+5][ny+5][x+5][y+5]){
                vtd[x+5][y+5][nx+5][ny+5= true;
                vtd[nx+5][ny+5][x+5][y+5= true;
                answer++;
            }
            x = nx;
            y = ny;
        }
        return answer;
    }
}
cs

#문제풀이 

진짜 이상한 곳에서 시간을 다 버렸다,,,, 

 

포인트는 양방향으로 체크를 해야하므로 방문 체크를 [현재x][현재y][다음x][다음y] 그리고 [다음x][다음y][현재x][현재y] 둘 다 해줘야한다.