[java] 프로그래머스 - 게임 맵 최단거리

0

[문제링크 - 프로그래머스 - 게임 맵 최단거리] https://school.programmers.co.kr/learn/courses/30/lessons/1844

class Solution {
    static int[] dx = {1, 0, -1, 0};
    static int[] dy = {0, -1, 0, 1};
    static boolean[][] visit;

    class Node {
        int x;
        int y;

        public Node(int x, int y){
            this.x = x;
            this.y = y;
        }
    }

    public int solution(int[][] maps) {
        int answer = 1;
        int n = maps.length;
        int m = maps[0].length;
        visit = new boolean[n][m];

        Queue<Node> queue = new LinkedList<>();
        queue.offer(new Node(0, 0));
        visit[0][0] = true;
        while (!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
                Node node = queue.poll();
                for(int j=0; j<4; j++){
                    int nx = node.x + dx[j];
                    int ny = node.y + dy[j];
                    if(nx == n-1 && ny == m-1){
                        return answer+1;
                    }
                    if(nx >= 0 && nx < n && ny >= 0 && ny < m && !visit[nx][ny] && maps[nx][ny]==1){
                        visit[nx][ny] = true;
                        queue.offer(new Node(nx, ny));
                    }
                }
            }
            answer++;
        }
        return -1;
    }
}
  • 문제는 현재 위치로부터 1칸을 세고 시작하는데, 그것을 인지 못하고 answer 초기 값을 0으로 해서 오답이 났었다.
  • n과 m의 값에 대해서 n = maps[0].length; m = maps.length; 아 아니라 반대인 이유
    오른쪽으로 한 칸 전진하고 싶어서 (0, 0)에 (1, 0)을 더하게 되면 nx = 1, ny = 0 이 된다.
    maps[1][0]으로 들어가서 원하는 값 0이 아니라 1이 나온다. 그래서 반대로 지정해줘야 한다.
profile
초심 잃지 않기

0개의 댓글

관련 채용 정보