class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
}
};
1091. 二进制矩阵中的最短路径
给你一个 n x n
的二进制矩阵 grid
中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1
。
二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即,(0, 0)
)到 右下角 单元格(即,(n - 1, n - 1)
)的路径,该路径同时满足下述要求:
0
。畅通路径的长度 是该路径途经的单元格总数。
示例 1:
输入:grid = [[0,1],[1,0]] 输出:2
示例 2:
输入:grid = [[0,0,0],[1,1,0],[1,1,0]] 输出:4
示例 3:
输入:grid = [[1,0,0],[1,1,0],[1,1,0]] 输出:-1
提示:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j]
为 0
或 1
原站题解
python3 解法, 执行用时: 348 ms, 内存消耗: 16.2 MB, 提交时间: 2022-08-01 10:48:04
from collections import dequeclass Solution:def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:if grid[0][0] != 0:return -1length = len(grid)if length == 1:return 1que = deque()visited = {}que.appendleft((0,0))visited[(0,0)] = Truestart = 1while que:for _ in range(len(que)):ind, con = que.pop()for pos_h, pos_v in [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]:new_ind = ind + pos_hnew_con = con + pos_vif 0 <= new_ind < length and 0 <= new_con < length and grid[new_ind][new_con] == 0 and not visited.get((new_ind, new_con)):if new_ind == length - 1 and new_con == length - 1:return start + 1que.appendleft((new_ind, new_con))visited[(new_ind, new_con)] = Truestart += 1return -1