BFS

何时应用BFS

  • 图的遍历

    • 层级遍历 ---- level order traversal

    • 由点及面 ---- clone graph, number of islands

    • 拓扑排序 --- alien dictionary

  • 简单图最短路径

    • word ladder

clone graph

word ladder

number of islands

Clone Graph

  • 实际写的时候思路还是不够清晰,基本功需要多练

  • BFS遍历每个Cur的neighbors

  • 同时用一个Map来存node和CloneNode

  • 对每个Cur.neighbor看是否在map里,如果在了就说明已经遍历过,不需要放到queue里

  • 如果不在的话就需要新建一个cloneNeighbor并放到map里

  • 最后把cloneNeighbor加入到cloneCur的neighbors

DFS 解法

Word Ladder

  • 先想简单的BFS解法,寻找隐式图最短路径

  • optimize: Bi-BFS

Number of island

  • 矩阵类BFS的基础题,由点及面BFS

  • 构建deltaX[ ] = {-1, 0, 0, 1}, deltaY = {0, -1, 1, 0}

  • BFS Queue存什么?可以是tuple{x, y}, 也可以是val = x * cols + y。 x = val / cols, y = val % cols

  • 还可以DFS, union find解

BFS解法

DFS解法

Flood Filling Distance Matrix

Walls and Gates

  • Multi-end BFS

  • 先找0

  • 然后bfs

  • 每次查看pop出来的坐标的邻居,如果还有INF,就更新距离

给一个2D matrix, 0表示路,1表示墙,给个start point和end point,求最短路径。(Twitter)

  • 最经典的BFS

Last updated

Was this helpful?