Bagas waters Mr. Tono’s plots along the stepping-stone paths: BFS with a queue of watering cans, DFS with a stack of seed trays or recursion. When does the…
Why it matters
BFS and DFS sit behind shortest paths, cycle detection, topological order, maze solvers, web crawlers and garbage collectors. Their three classic bugs happen here for real: forgotten visited marks, recursion that fills the call stack, and DFS used to find the shortest way.
The key idea
A queue or a stack: that is all
Common mistakes
The traversal goes round and round, never ending A graph with a cycle and no dikunjungi set lets the same node in again and again. Mark a node when it goes into the frontier (or when it is taken, as long as you are consistent).
Recursive DFS crashes: Maximum call stack size exceeded on a deep graph Every recursive call stacks a frame on the engine’s call stack, which is limited (a few thousand in many browsers). For deep graphs use a stack of your own (iterative).
Using DFS for the shortest way, and it is not the shortest DFS does not promise the shortest way. For an unweighted graph use BFS; for a weighted one, Dijkstra.
Try it in this playground
BFS to the end Watch the order spread layer by layer.
DFS to the end One branch to its end first, then back.
See a pass skipped A plot stacked twice comes off again, then is skipped.
Run without marks The cycle makes the watering never end.