基本思路:
从起点出发,每次都尝试访问同一层的节点,如果同一层都访问完了,再访问下一层,最后广度优先搜索找到的路径就是从起点开始的最短合法路径。
模板:
1.不需要确定遍历的层数
while queue 不空:
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未访问过:
queue.push(该节点)
2.需要确定遍历的层数
level = 0
while queue 不空:
size = queue.size()
for i in range(size):
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未被访问过:
queue.push(该节点)
level += 1;
例1:腐烂的橘子
在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:
0 代表空单元格; 1 代表新鲜橘子; 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。
输入:grid = [[2,1,1],[1,1,0],[0,1,1]]
输出: 4
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0])
queue = []
for i in range(M):
for j in range(N):
if grid[i][j] == 2:
queue.append((i,j))
dirs = [(0,1), (0,-1), (1,0), (-1,0)]
t = 0
while queue:
size = len(queue)
for i in range(size):
x, y = queue.pop(0)
for dx, dy in dirs:
new_x = x + dx
new_y = y + dy
if new_x < 0 or new_x >= M or new_y < 0 or new_y >= N or grid[new_x][new_y] != 1:
continue
grid[new_x][new_y] = 2
queue.append((new_x,new_y))
if queue:
t += 1
for i in range(M):
for j in range(N):
if grid[i][j] == 1:
return -1
return t
例2:01矩阵元素最近距离
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]
class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
M = len(mat)
N = len(mat[0])
queue = []
visited = [[0] * N for _ in range(M)]
res = [[0] * N for _ in range(M)]
for i in range(M):
for j in range(N):
if mat[i][j] == 0:
visited[i][j] = 1
queue.append((i,j))
dirs = [(0,1), (0,-1), (1,0), (-1,0)]
step = 0
while queue:
size = len(queue)
for i in range(size):
x, y = queue.pop(0)
if mat[x][y] == 1:
res[x][y] = step
for dx, dy in dirs:
new_x, new_y = x + dx, y + dy
if new_x < 0 or new_x >=M or new_y < 0 or new_y >= N or visited[new_x][new_y] == 1:
continue
queue.append((new_x, new_y))
visited[new_x][new_y] = 1
step += 1
return res