Learning pathsPricingChecking sign-in…
Trees, graphs and optimization

Depth-first search

Explore a branch while preserving traversal state.

Depth-first traversal is a control strategy; visited state, components, and recursion limits depend on the task.

Mechanism and state

For grid islands, scan every cell and start a traversal only at unvisited land. A flood traversal visits every orthogonally connected land cell, so one start means one component. Separate visited flags preserve the input. Recursive DFS is concise, but a 10,000-cell connected path can exceed Java’s call stack; an explicit stack or queue is safer for full input bounds. For tree postorder, a stack entry must also store where execution resumes and child results; pushing nodes alone does not automatically provide bottom-up evaluation. Same-position and mirrored-position comparisons need nullable Pair wrappers rather than null deque entries. Component area counts popped coordinates instead of traversal starts. Flood Fill can use the replacement color as a discovery mark only after a same-color guard. Surrounded Regions first certifies all boundary-connected O cells, then captures the complement. Pacific Atlantic reverses downhill edges and keeps an independent mask for each ocean. Clone Graph registers a fresh copy by source identity before following its edges; this handles cycles, self-loops, and ordered parallel references. Directed dependency problems need graph state beyond component membership: a topological prefix records completed prerequisites, while eventual safety certifies every outgoing continuation. Strictly increasing matrix values create a DAG without an explicit adjacency list, allowing longest-suffix evaluation from maxima. DSA-124 uses a different visited lifetime from component traversal: a coordinate is claimed only while its frame remains on the active candidate-word path. Each explicit frame retains a word index and next direction, so child failure resumes the parent without repeating earlier neighbors.

Why the pattern works

A traversal frontier contains only cells connected to its start. Every reachable land neighbor is eventually discovered, and visited marking prevents repeated work. Once that component is exhausted, a later unvisited start cannot belong to it. A complete scan finds one start per component. Reachability certificates extend one legal edge at a time. The complement of complete boundary reachability is exactly the captured region. Reversing every edge preserves the equivalence between reaching an ocean forward and being reachable from its shore backward. For graph copying, a partial identity bijection ensures every copied edge has exactly the corresponding endpoint even when values repeat. A directed cycle prevents any of its vertices from being the first topologically completed member. In a finite graph, an infinite continuation exists exactly when a cycle is reachable. Universal safety therefore peels vertices only after all successors are safe. Strict-value longest paths obey L(v)=1+max L(greater neighbor), with sinks at one.

Work through an example

["110","010","001"] contains two components: the top-left three cells and the isolated final cell. Diagonal contact does not join them. Changing adjacency to eight directions changes the problem contract.

Where the reasoning fails

A directed cycle needs active versus finished states, not just one visited bit. A shortest unweighted path needs layer/distance reasoning, not arbitrary DFS visitation order. Always separate representation costs, including O(V²) scanning for an adjacency matrix. A global two-arm path is not a one-arm summary that can be extended by an ancestor. LCA compares identities and verifies target membership; repeated values are not object IDs. Read-only grids may share row objects because vertices are coordinates. Coordinate mutation APIs reject shared rows before writing, since one write could otherwise affect unrelated coordinates. Do not confuse a global discovery mark with Word Search path-local ownership. Reverse ocean flow uses >=, not <=; plateau equality is legal. A value-keyed clone map merges distinct nodes, and a neighbor set destroys edge order and multiplicity. Reaching one terminal is existential and does not prove universal termination. A residual blocked vertex can lead into a cycle without lying on it. For an increasing path, a visited bit is not a numeric suffix answer, and nondecreasing moves destroy strict-order acyclicity. A permanent global seen array suitable for graph component discovery loses valid Word Search branches. Path-local marks must be released on both ordinary backtracking and successful cleanup; source-board mutation is unnecessary.

Reconstruct the reasoning

Compare recursive DFS, explicit DFS, and BFS for this grid. State what remains the same in correctness and what changes in memory or recursion safety. Compare Number of Islands and Maximum Area on [[1,1,0],[0,1,0],[1,0,1]]. Identify which cells Flood Fill may change and why matching the old color requires a guard. Prove why a diagonal O escape is invalid, then reverse one downhill ocean path. Draw the identity mapping for two equal-valued graph nodes with a self-loop and two parallel edge occurrences. Compare 0→terminal plus 0→self-loop with a fully terminating DAG. Identify which residual vertices are actual cycle members. For a height plateau, explain why no strict edge exists; for a shared increasing suffix, derive its numeric recurrence before choosing recursive memoization or reverse topological layers.

Apply this foundation

Your study notes