Problem Solving/Programmers
[Level 2] 게임 맵 최단거리
kmkunk
2022. 4. 7. 10:59
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;
}
}
}
}
}