Traversal
Visiting every vertex reachable from a start, systematically. BFS walks
outward in rings using a queue; DFS commits to one branch and plunges using a
stack (explicit, or the call stack via recursion). Both are the same loop with
two knobs - the neighbour function, and how you track visited.
The mechanics, the correctness argument for why BFS's first arrival is always
shortest, and the traps that come from marking visited at the wrong moment
all live on the learn page: Traversal. The
problems below are that engine with one knob turned.
1971. Find if Path Exists in Graph
1971. Find if Path Exists in Graph
DFS - RecursiveO(V + E) time best timeO(V + E) aux best space
DFS - IterativeO(V + E) time best timeO(V + E) aux best space
BFS - IterativeO(2V + 2E) timeO(V + E) aux best space
DSU↗ DSU on GraphO(3n + E * α(n) + 2 * α(n)) timeO(3n) aux
DFS - Recursive
FIG. FIND IF PATH EXISTS IN GRAPH● INTERACTIVE
visualization loads as you reach it
133. Clone Graph
133. Clone Graph
Recursive DFSO(V + E) time best timeO(3V) aux best space
Iterative DFS (Stack)O(2E + 1) timeO(2V + E + 1) aux
Iterative BFS (Queue)O(2E + 1) timeO(2V + E + 1) aux
Iterative BFS (Parent-Linked)O(2E + 1) timeO(2V + E + 1) aux
Recursive DFS
FIG. 133 CLONE GRAPH RECURSIVE● INTERACTIVE
visualization loads as you reach it
2101. Detonate the Maximum Bombs
2101. Detonate the Maximum Bombs
DFS - RecursiveO(n2 + n * (2E + 1)) timeO(3n + E) aux best space
DFS - IterativeO(n2 + n * (2E + 1)) timeO(2n + 2E + 1) aux
BFS - IterativeO(n2 + n * (2E + 1)) timeO(2n + 2E + 1) aux
DFS - Recursive
FIG. 2101 DETONATE THE MAXIMUM BOMBS● INTERACTIVE
visualization loads as you reach it