1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public int nearestExit(char[][] maze, int[] entrance) {
int m = maze.length, n = maze[0].length;
Deque<int[]> emptyCells = new ArrayDeque<>();
int steps = 0;
Set<String> visited = new HashSet<>();
emptyCells.offer(entrance);
visited.add(entrance[0] + "," + entrance[1]);
int[][] directions = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
while (!emptyCells.isEmpty()) {
for (int i = emptyCells.size(); i > 0; i--) {
int[] currPos = emptyCells.poll();
for (int[] direction : directions) {
int newRow = currPos[0] + direction[0];
int newCol = currPos[1] + direction[1];
if (!isOutOfBound(m, n, newRow, newCol) && maze[newRow][newCol] == '.'
&& visited.add(newRow + "," + newCol)) {
if (newRow == 0 || newRow == m - 1 || newCol == 0 || newCol == n - 1) {
return steps + 1;
} else {
emptyCells.offer(new int[] { newRow, newCol });
}
}
}
}
steps += 1;
}
return -1;
}

private boolean isOutOfBound(int totalRow, int totalCol, int currRow, int currCol) {
return currRow < 0 || currRow >= totalRow || currCol < 0 || currCol >= totalCol;
}
}

经典BFS.

时间复杂度: O(m * n)
空间复杂度: O(m * n)