Patterns

GB · Pattern 16

Graph BFS / DFS

Traverse graphs using BFS (shortest path, level-by-level) or DFS (connected components, path existence). Always track visited nodes to avoid cycles.

Graph BFS / DFS
Time
O(V + E)
Space
O(V)

Spot it when

  • Count connected components / islands
  • Shortest path in unweighted graph (BFS)
  • Flood fill, bipartite check
  • Multi-source BFS (rotting oranges)