1091. Shortest Path in Binary Matrix (M)
Shortest Path in Binary Matrix (M)
题目
In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k
if and only if it is composed of cells C_1, C_2, ..., C_k
such that:
- Adjacent cells
C_i
andC_{i+1}
are connected 8-directionally (ie., they are different and share an edge or corner) C_1
is at location(0, 0)
(ie. has valuegrid[0][0]
)C_k
is at location(N-1, N-1)
(ie. has valuegrid[N-1][N-1]
)- If
C_i
is located at(r, c)
, thengrid[r][c]
is empty (ie.grid[r][c] == 0
).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
Example 1:
Input: [[0,1],[1,0]]
Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Note:
1 <= grid.length == grid[0].length <= 100
grid[r][c]
is0
or1
题意
给定一个矩阵,其中值为1的格子不能走,为0的格子可以走。从每个格子出发有8个方向可走。求从左上到右下的最短路径。
思路
每条边的权值都为1,直接用BFS搜索最短路。
代码实现
Java
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
if (grid[0][0] == 1) return -1;
int steps = 0;
int n = grid.length;
Queue<int[]> q = new ArrayDeque<>();
boolean[][] visited = new boolean[n][n];
q.offer(new int[]{0, 0});
visited[0][0] = true;
while (!q.isEmpty()) {
int size = q.size();
steps++;
while (size > 0) {
int[] cur = q.poll();
int i = cur[0], j = cur[1];
if (i == n - 1 && j == n - 1) {
return steps;
}
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (x != 0 || y != 0) {
int nextI = i + x, nextJ = j + y;
if (isValid(nextI, nextJ, n) && !visited[nextI][nextJ] && grid[nextI][nextJ] == 0) {
visited[nextI][nextJ] = true;
q.offer(new int[]{nextI, nextJ});
}
}
}
}
size--;
}
}
return -1;
}
private boolean isValid(int i, int j,int n){
return i < n && i >= 0 && j < n && j >= 0;
}
}