广度优先搜索(Breadth-First Search, BFS) 是一种基于队列实现的层次遍历算法,适用于最短路径、状态转移、连通性等问题。其核心思想是“层层扩展”,从起点出发,逐层访问所有可达节点。
本文从基础概念到经典题型进行系统分类与解析,涵盖从入门到进阶的所有常见问题。
pythondef levelOrder(root):
if not root: return []
queue = collections.deque([root])
res = []
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(level)
return res
level[::1 if len(res) % 2 == 0 else -1]
)beginWord
到 endWord
的最短转换序列pythondef numIslands(grid):
if not grid: return 0
directions = [(-1,0),(1,0),(0,-1),(0,1)]
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
queue = collections.deque([(i,j)])
grid[i][j] = '0' # 标记已访问
while queue:
x, y = queue.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == '1':
queue.append((nx, ny))
grid[nx][ny] = '0'
count += 1
return count
pythondef updateMatrix(mat):
m, n = len(mat), len(mat[0])
queue = collections.deque()
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
queue.append((i,j))
else:
mat[i][j] = -1 # 未访问标记
directions = [(-1,0),(1,0),(0,-1),(0,1)]
while queue:
x, y = queue.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and mat[nx][ny] == -1:
mat[nx][ny] = mat[x][y] + 1
queue.append((nx, ny))
return mat
directions = [(-1,0),(1,0),(0,-1),(0,1)]
简化代码level_size = len(queue)
控制当前层遍历类型 | 经典题目 |
---|---|
树遍历 | 102. 层序遍历、103. 锯齿遍历 |
图最短路径 | 127. 单词接龙、1334. 阈值距离城市 |
网格问题 | 200. 岛屿数量、1091. 最短路径 |
状态转移 | 752. 打开转盘锁、773. 滑动谜题 |
多源BFS | 542. 01矩阵、994. 腐烂橘子 |
BFS 的核心在于层次遍历与最短路径搜索。
掌握要点:
📌 推荐练习顺序:树的层序遍历 → 网格类问题 → 状态转移 → 多源BFS → 图最短路径
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!