codebrew.ai

Graph Traversal (BFS & DFS) Pattern

BFS explores level by level (shortest paths in unweighted graphs); DFS dives deep before backtracking (connectivity, cycles, topological order). Most grid and graph problems reduce to one of the two.

Typical complexity: O(V + E) time, O(V) space

When to use it

  • The problem is about reachability, connected components, or shortest hops.
  • You're traversing a grid, tree, or explicit graph.
  • You need to detect cycles or explore all paths.

Practice problems

Read the approach or generate an interactive, step-by-step lesson:

Deep dive

BFS vs DFS: Choosing the Right Graph Traversal for the Job

Understand the difference between breadth-first and depth-first search, when each traversal is the right fit, and how they show up in trees, graphs, and grids.

Master graph traversal (bfs & dfs) by doing

codebrew.ai turns each problem into an interactive lesson — trace the algorithm variable by variable until the pattern clicks.

Start a free lesson

Related patterns