Learn / Graphs

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.

UseSearch
fewest edges from a startBFS
copy a grapheither, with a map from old to new
entry and exit times (ancestor checks)DFS
all simple paths, longest pathDFS with backtracking (exponential)
Euler path or circuitdegree 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

0 of 9 solved

Check yourself

Which structure does BFS use?

Why mark a vertex when it is added to the BFS queue rather than when it is removed?

When copying a graph, what does the map from original to copy also act as?

What does an Euler circuit need, besides connected edges?