Visit every node using depth-first or breadth-first strategies.
Graph traversal visits every reachable node exactly once. DFS goes as deep as possible before backtracking — implemented recursively or with an explicit stack. BFS visits all neighbors at the current depth before going deeper — uses a queue. Both run in O(V+E).
O(V + E)
O(V) for visited + recursion/queue
Learn the core patterns in this topic. Each block explains when to use the pattern, the intuition behind it, and a compact code example.
go deep, backtrack, use recursion or stack; finds paths and cycles
level by level with a queue; finds shortest path in unweighted graph
essential to avoid infinite loops in cyclic graphs
run DFS/BFS from every unvisited node
2-color with BFS; odd cycle means not bipartite
BFS/DFS on a 2D grid from a starting cell