import java.util.*;

class Solution {
    public int n;
    public int m;
    public int[] dx = new int[]{1,-1,0,0};
    public int[] dy = new int[]{0,0,1,-1};
    public int[][] copy;
    
    public int solution(int[][] maps) {
        n = maps.length;
        m = maps[0].length;
        copy = new int[n][m];
        
        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) { copy[i][j] = maps[i][j]; }
        }
        
        bfs(0,0);
        
        return copy[n-1][m-1]==1 ? -1 : copy[n-1][m-1];
    }
    
    public void bfs(int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{i,j});
        
        while(!queue.isEmpty()) {
            int[] a = queue.poll();
            int x = a[1];
            int y = a[0];
            for(int k=0; k<4; k++) {
                int nx = x+dx[k];
                int ny = y+dy[k];
                if(nx>=0 && ny>=0 && nx<m && ny<n && copy[ny][nx]==1) {
                    queue.add(new int[]{ny,nx});
                    copy[ny][nx] = copy[y][x]+1;
                }
            }
        }
    }
}

'Problem Solving > Programmers' 카테고리의 다른 글

[Level 2] 점프와 순간 이동  (0) 2022.04.07
[Level 2] 이진 변환 반복하기  (0) 2022.04.07
[Level 2] 카카오프렌즈 컬러링북  (0) 2022.04.07
[Level 2] 모음 사전  (0) 2022.04.06
[Level 2] 교점에 별 만들기  (0) 2022.04.06