상세 컨텐츠

본문 제목

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

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2025. 2. 3. 13:25

본문

       문제 요약        

- 문제

 

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 
    }
}

 

728x90

관련글 더보기