코드
import java.util.*;
class Solution {
static int[][] move ={ { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };;
static boolean[][] visited;
static int n,m;
static int cnt = 0;
public int solution(int [][] maps) {
n = maps.length;
m = maps[0].length;
visited = new boolean[n][m];
int answer = BFS(0, 0, maps);
return answer;
}
static int BFS(int x, int y, int[][] maps){
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{x, y});
visited[x][y] = true;
while (!queue.isEmpty()) {
int[] temp = queue.poll();
for (int i = 0; i < 4; i++) {
int dx = temp[0] + move[i][0];
int dy = temp[1] + move[i][1];
if (dx>=0 && dx <n && dy>=0 && dy<m && !visited[dx][dy] && maps[dx][dy] == 1) {
visited[dx][dy] = true;
queue.add(new int[]{dx, dy});
maps[dx][dy] = maps[temp[0]][temp[1]] + 1;
}
}
}
if(visited[n-1][m-1]) {
return maps[n-1][m-1];
} else {
return -1;
}
}
}