다희의 코딩 성장일기

[프로그래머스] level2. 게임 맵 최단거리 (자바 JAVA) 본문

Algorithm/프로그래머스

[프로그래머스] level2. 게임 맵 최단거리 (자바 JAVA)

ilmiodiario 2021. 8. 27. 14:14

[ 문제 ]  [프로그래머스] level2. 게임 맵 최단거리 (자바 JAVA)

 

문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/1844

 

코딩테스트 연습 - 게임 맵 최단거리

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr


# 접근 방법 및 풀이 

 

  • BFS로 풀면된다!
  • 자세한건 코드참조

# 주의할 점 

 

  • 보통 벽을 1로하는데 여기선 벽이 0이다.

 

JAVA 코드
import java.util.*;
class Solution {
    static class Node{
        int r, c, cnt;
        public Node(int r, int c, int cnt){
            this.r = r;
            this.c = c;
            this.cnt = cnt;
        }
    }
    static int dr[] = {-1, 1, 0, 0};
    static int dc[] = {0, 0, -1, 1};
    public int solution(int[][] maps) {
        int answer = -1;
        int R = maps.length;
        int C = maps[0].length;
        boolean visit[][] = new boolean [R][C];
        Queue<Node> queue = new LinkedList<>();
        visit[0][0] = true;
        queue.add(new Node(0, 0, 1));
        while(!queue.isEmpty()){
            Node node = queue.poll();
            if(node.r == R-1 && node.c == C-1){
                answer = node.cnt;
                return answer;
            }
            for(int d = 0 ; d < 4; d++){
                int nr = node.r + dr[d];
                int nc = node.c + dc[d];
                if(nr < 0 || nc < 0 || nr >= R || nc >= C || visit[nr][nc] || maps[nr][nc] == 0)
                    continue;
                visit[nr][nc] = true;
                queue.add(new Node(nr, nc, node.cnt+1));
            }
        }
        return answer;
    }
}

 

 

 

REVIEW

Comments