https://school.programmers.co.kr/learn/courses/30/lessons/1844
문제
풀이
최단거리를 구하는 문제. 당연히 BFS를 사용해야한다.
코드
import java.util.*;
class Solution {
static boolean[][] check;
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, 1, 0, -1};
static int n, m;
public int solution(int[][] maps) {
n = maps.length;
m = maps[0].length;
check = new boolean[n][m];
int answer = bfs(0, 0, maps);
return answer;
}
public int bfs(int x, int y, int[][] map){
Queue<int[]> queue = new LinkedList<>();
check[x][y] = true;
queue.add(new int[]{x, y, 1});
while(!queue.isEmpty()){
int[] now = queue.poll();
if(now[0]==n-1 && now[1]==m-1) return now[2];
for(int i=0; i<4; i++){
int nx = now[0]+dx[i];
int ny = now[1]+dy[i];
if(nx<0 || ny<0 || nx>=n || ny>=m) continue;
if(check[nx][ny] || map[nx][ny]==0) continue;
check[nx][ny] = true;
queue.add(new int[]{nx, ny, now[2]+1});
}
}
return -1;
}
}