BFS and DFS
Breadth-first search visits vertices in order of distance from the start, using a queue. Depth-first search follows one path as deep as it can before backing up, using recursion or a stack. Both mark vertices as visited so nothing is processed twice, and both run in O(V + E). Many problems are one of them with a small twist.
How to recognise it
- Visit everything reachable from a vertex.
- Shortest paths when every edge counts the same (BFS).
- Exploring all paths, copying a graph, or checking what is below a vertex in a tree (DFS).
The two searches
bfs(s): queue = [s]; seen = {s}
while queue: u = pop front; visit u
for v in adj[u]: if v not in seen: seen.add(v); push v
dfs(u): seen.add(u); visit u
for v in adj[u]: if v not in seen: dfs(v)
Vertices, edges, adjacency lists and the other words used here are on the Structures page.
| Use | Search |
|---|---|
| fewest edges from a start | BFS |
| copy a graph | either, with a map from old to new |
| entry and exit times (ancestor checks) | DFS |
| all simple paths, longest path | DFS with backtracking (exponential) |
| Euler path or circuit | degree counts plus one connectivity check |
Common mistakes
- Forgetting the visited set, which loops forever on a cycle.
- Using BFS distances when edges have different weights.
Problems
- Traversal Techniquesmediumguide ready
- Implement BFS algorithmmediumguide ready
- Implement DFS Algomediumguide ready
- Clone Graphmediumguide ready
- Oliver and the Gamemediumguide ready
- Find if there is a path of more thank length from a sourcemediumguide ready
- Paths to travel each nodes using each edge(Seven Bridges)hardguide ready
- Vertex Cover Problemhardguide ready
- Chinese Postman or Route Inspectionhardguide ready