class Solution {
static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int nearestExit(char[][] maze, int[] entrance) {
int m = maze.length;
int n = maze[0].length;
int[][] visited = new int[m][n];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{entrance[0], entrance[1]});
visited[entrance[0]][entrance[1]] = 1;
int res= 0 ;
while (!queue.isEmpty()) {
res++;
int sizes = queue.size();
for(int i = 0;i <sizes;i++) {
int[] cur = queue.poll();
for(int j = 0;j < 4;j++){
int newx = cur[0] + dir[j][0];
int newy = cur[1] + dir[j][1];
if(newx < 0 || newx >= m || newy < 0 || newy >= n || visited[newx][newy] == 1||maze[newx][newy] == '+') continue;
if(newx == 0 || newx == m - 1 || newy == 0 || newy == n - 1) return res;
queue.offer(new int[]{newx, newy});
visited[newx][newy] = 1;
}
}
}
return -1;
}
}
不能够在for循环里面有queue.size
应该先获取queue.size 到一个sizes = queue.size(), 然后遍历sizes,不然容易出错