Why it matters

Graph traversal underlies many problems: network reachability, dependency resolution, maze solving, social network analysis. Understanding BFS and DFS is foundational.

Advertisement

The architecture

BFS: use a queue. Enqueue start; while queue is non-empty, dequeue, mark visited, enqueue unvisited neighbors.

DFS: use a stack (or recursion). Push start; while stack non-empty, pop, mark visited, push unvisited neighbors. Recursive version is often cleaner.

Graph traversalBFSqueue, level-by-levelDFSstack, path-by-pathVisited setprevent revisitsBFS finds shortest unweighted paths; DFS finds topological order, SCCs, cycles
Two traversal strategies.
Advertisement

How it works end to end

BFS applications: shortest path in unweighted graph, level-order tree traversal, connectivity, bipartite check.

DFS applications: topological sort (order tasks by dependency), cycle detection, strongly connected components (Tarjan, Kosaraju), maze solving.

Bidirectional BFS: search from both ends simultaneously. Meets in middle. Much faster for shortest path in large graphs.