1091. Shortest Path in Binary Matrix,奇怪的路徑 python 解
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
- All the visited cells of the path are
0. - All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
Example 1:

Input: grid = [[0,1],[1,0]] Output: 2
Example 2:

Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1
這種題目就是給你一個圖,然後要你找最短路徑,而且是完全沒有weight 或是所有weight都一樣這就是老題目: shorted graph of unweighted graph=bfs (且已經知道起點跟終點啦)使用bfs 並且找level最後回傳level在最右下角 即可參考底下的python code 唷
class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: #bfs n=len(grid) if grid[0][0]==1: return -1 visited={(0,0)} queue=deque([(0,0)]) level=dict() level[(0,0)]=1 while queue: for i in range(len(queue)): node=queue.popleft() x,y=node for dx,dy in {(-1,0),(1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)}: if x+dx<n and x+dx>=0 and y+dy<n and y+dy>=0 and grid[x+dx][y+dy]==0: if (x+dx,y+dy) in visited: continue visited.add((x+dx,y+dy)) queue.append((x+dx,y+dy)) level[(x+dx,y+dy)]=level[(x,y)]+1 if (n-1,n-1) in level: return level[(n-1,n-1)] else: return -1
留言
張貼留言