1091. Shortest Path in Binary Matrix

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
35
36
37
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};

public int shortestPathBinaryMatrix(int[][] grid) {
int m = grid.length, n = grid[0].length;

int pathLength = 0;
boolean[][] visited = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>();
if (grid[0][0] == 0) {
queue.offer(new int[]{0, 0});
visited[0][0] = true;
}

while (!queue.isEmpty()) {
pathLength++;

for (int k = queue.size(); k > 0; k--) {
int[] cell = queue.poll();
visited[cell[0]][cell[1]] = true;
if (cell[0] == m - 1 && cell[1] == n - 1) {
return pathLength;
}

for (int[] direction : DIRECTIONS) {
int i = cell[0] + direction[0], j = cell[1] + direction[1];
if (i >= 0 && i < m && j >= 0 && j < n && grid[i][j] == 0 && !visited[i][j]) {
queue.offer(new int[]{i, j});
visited[i][j] = true;
}
}
}
}

return -1;
}
}

注意标记已访问状态的时机,防止节点重复入队导致 TLE。

References

1091. Shortest Path in Binary Matrix