给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1 。
二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即,(0, 0))到 右下角 单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:
- 路径途经的所有单元格都的值都是 0 。
 - 路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
 
畅通路径的长度 是该路径途经的单元格总数。
题目链接:https://leetcode.cn/problems/shortest-path-in-binary-matrix/
# 解题思路
BFS 模板
- 初识状态
 - 转移方法
 - 遍历
 
# 执行结果

# 代码
class Solution {  | |
public int shortestPathBinaryMatrix(int[][] grid) {  | |
if (grid[0][0] == 1) return -1;  | |
int n = grid.length;  | |
int[][] dir = new int[][] <!--swig0-->;  | |
int[][] dis = new int[n][n];  | |
Queue<int[]> que = new ArrayDeque<>();  | |
dis[0][0] = 1;  | |
que.offer(new int[] {0, 0});  | |
while (!que.isEmpty()) {  | |
for (int i = que.size(); i > 0; --i) {  | |
int[] cur = que.poll();  | |
int x = cur[0], y = cur[1];  | |
if (x == n - 1 && y == n - 1) return dis[x][y];  | |
for (int[] d : dir) {  | |
int nx = x + d[0], ny = y + d[1];  | |
if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] == 0 && dis[nx][ny] == 0) {  | |
dis[nx][ny] = dis[x][y] + 1;  | |
que.offer(new int[] {nx, ny});  | |
                    } | |
                } | |
            } | |
        } | |
return -1;  | |
    } | |
} |