LC.P1091[二进制矩阵中的最短路径]

方法一:BFS

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
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
if (grid[0][0] == 1) return -1;
int n = grid.length;
grid[0][0] = 1;
Deque<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{0, 0});
int ans = 1;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
int[] cur = queue.poll();
int x = cur[0], y = cur[1];
if (x == n - 1 && y == n - 1) return ans;
for (int nx = x - 1; nx <= x + 1; ++nx) {
for (int ny = y - 1; ny <= y + 1; ++ny) {
if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if (grid[nx][ny] == 1) continue;
grid[nx][ny] = 1;
queue.offer(new int[]{nx, ny});
}
}
}
++ans;
}
return -1;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n^2)$