Depth-first search
深度优先搜索
Follow a branch with an explicit stack, prove finite-graph reachability, and distinguish path memory from a global visited set.
depth-first-searchTry one corridor until it ends
A map offers two exits from S: corridor A and the goal G. Corridor A leads to B, which also leads to G. A search that follows A before returning to the junction can report S–A–B–G even though S–G is available. It has found a route, but not the shortest one.
Depth-first search (DFS) explores one branch before its siblings. When there is no eligible continuation, it backs up to the most recent unfinished choice. A last-in, first-out stack records those choices. The name describes the order of exploration, not a promise to find the globally deepest state or the cheapest solution. CS188, section 1.3.1
A path and a set answer different questions
Our graph is finite and directed. Vertex identifiers are hashable; adjacency lists describe a fixed graph; an absent entry means no outgoing edges. The state must contain all information relevant to future legal moves and the goal test. If two visits have the same identifier but different keys in an inventory, they are not the same state for this purpose.
The implementation keeps three structures. path is the current route. stack remembers where to resume each route vertex’s adjacency scan. seen contains every discovered vertex, including branches that have already finished. A vertex is added to seen when entered, so each is entered at most once.
The key invariant is simple: the stack’s vertex sequence equals path, and successive path vertices are connected by graph edges. Taking an unseen neighbor extends both structures; finishing a vertex removes it from both. Every returned path is therefore a valid route from the start.
Why is a global seen set safe for this reachability question? A vertex’s outgoing edges depend only on the vertex, not the route used to reach it. Once the first visit has fully explored them, a second visit cannot reveal a new outgoing possibility. On a finite graph, each vertex is entered at most once and each adjacency iterator eventually finishes. If the search exhausts its stack, every reachable vertex has been examined. Thus a reachable goal is found, and an unreachable goal leads to termination with failure.
This qualification repairs a common misunderstanding. Unrestricted tree DFS can fail to terminate on a cycle or an infinite branch; finite graph DFS with duplicate detection terminates. AIMA provides separate tree-search and graph-search functions. Their different handling of repeated states is part of the algorithm, not a small implementation detail. AIMA Python, depth-first variants at the fixed commit
Store the next choice instead of using Python recursion
This complete program returns a path containing both endpoints, or None if the goal is unreachable. It scans each adjacency list in its supplied order. Iterators preserve a parent’s unfinished work while a child’s branch is explored. Python’s function-call recursion limit does not bound this explicit stack.
def dfs(graph, start, goal):
# Adjacency values must be finite, repeatable sequences.
seen = {start}
path = [start]
stack = [(start, iter(graph.get(start, ())))]
if start == goal:
return path.copy()
while stack:
u, children = stack[-1]
try:
v = next(children)
except StopIteration:
stack.pop()
path.pop()
continue
if v in seen:
continue
seen.add(v)
path.append(v)
if v == goal:
return path.copy()
stack.append((v, iter(graph.get(v, ()))))
return None
graph = {'S': ['A', 'G'], 'A': ['S', 'B'],
'B': ['G'], 'G': []}
assert dfs(graph, 'S', 'G') == ['S', 'A', 'B', 'G']
assert dfs(graph, 'S', 'S') == ['S']
assert dfs(graph, 'S', 'missing') is None
assert dfs({'S': ['S']}, 'S', 'G') is None
assert dfs({None: [0], 0: ['end']}, None, 'end') == [None, 0, 'end']
chain = {i: [i+1] for i in range(3000)}
assert len(dfs(chain, 0, 3000)) == 3001
print(dfs(graph, 'S', 'G'))
The first result is ['S', 'A', 'B', 'G']. The back edge from A to S is skipped because S is already discovered. The direct edge S–G has not yet been inspected when the deeper branch finds G. Reversing S’s adjacency list would return the direct route. Ordering changes the answer’s route and often the runtime; it does not create an optimality guarantee.
Returning a copy matters because path is mutable working storage. The implementation does not copy an entire path for every pushed node. It appends and removes one vertex while searching and copies only the final result.
The memory bound depends on what you remember
For the reachable part of an explicit graph, the implementation takes time with expected constant-time hashing and constant-time adjacency-iterator steps. The global set uses space; the current path and iterator stack contain at most vertices. The graph’s already supplied adjacency storage is separate. Even a shallow search can accumulate a large seen set across many completed branches.
For tree search, let bound the number of children and bound depth. A conventional frontier that eagerly stores siblings uses space. With constant-size, lazy successor iterators and no global visited set, traversal storage can instead be . Neither statement gives our graph implementation an total-memory guarantee. Generators that internally materialize large child lists also invalidate the constant-size-iterator assumption.
For a full tree with fixed , the number of nodes through depth is
Searching the whole tree is exponential in depth, despite modest path storage. For a single chain, , the count is only ; the fraction above must not be evaluated with a zero denominator. The familiar tree bounds describe path exploration and need not match the explicit graph’s and . CS188, search-tree complexity conventions
Infinite graphs require a separate warning. A chain with endlessly new states can occupy the first branch forever even with a seen set. A goal may exist on a later branch and never be reached. No amount of cycle checking removes an infinite sequence of distinct states.
DFS also ignores edge costs. Use BFS for minimum edge count or uniform-cost search for nonnegative costs under its stated conditions. If a search uses a depth limit, a bare global visited set needs reconsideration: reaching a state with little remaining depth is not equivalent to reaching it later with more. Iterative deepening develops that case.
Predict the path before running it
- Why does the example return three edges when a one-edge route exists? Answer: the A branch is explored first and reaches G before the root’s next choice is inspected. DFS optimizes neither edge count nor cost.
- Can we remove a vertex from
seenwhenever it leavespathand retain the same complexity proof? Answer: no. That becomes path-based cycle checking; another branch may explore the vertex again. The once-per-vertex argument no longer applies. - Does the 3,000-edge chain require increasing Python’s recursion limit? Answer: no. The program uses an explicit stack. It still needs enough heap memory for its path, set and frames.
- Does a global visited set make DFS complete on an infinite graph of distinct states? Answer: no. It can follow a never-ending fresh branch and postpone another branch containing a goal indefinitely.
Measure exploration and storage separately
For a small experiment, compare the given graph with one whose S neighbors are reversed. Record the returned path length and the number of first visits. Then build a broad finite tree and compare DFS with BFS, measuring both maximum frontier size and the size of any visited set. Reporting only stack depth can hide most of a graph search’s memory use.
AIMA’s implementations are useful for comparing control flow, but their Node objects and frontier membership operations differ from this code’s iterator frames and hash set. Complexity should be read from the implementation being measured. For the next problem, keep the low path-storage idea while asking for a shallowest solution without knowing its depth: that leads to iterative deepening. Graph traversal itself does not train a model; it is a tool used inside many larger reasoning and planning systems.
Make a prediction, then check
Can DFS with a global visited set count its total memory only from current path depth?
Learning objectives
- Use stack/path invariants to justify returned routes and distinguish finite graphs from infinite tree search.
- Analyze time/memory from actual visited storage and successor generation,and construct a nonshortest returned route.
Prerequisites & connections
Explore related knowledge →References
- CS188 Textbook — Uninformed Search
UC Berkeley CS188 course contributors - AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: inspected fixed source code and course/paper material,independent graph-distance comparison,executed full programs and bilingual rereading; no independent human peer review.
- Reread bilingual invariants,finite-graph conditions,chain and branching bounds; analyzed iterators,seen,path copying and goal handling in actual code.
- Executed5 search checks:all4096 four-vertex directed graphs with self-loops against Floyd–Warshall distances;depth budget/revisit case,four full-tree counts,5000-level explicit stack and input boundaries.All93 site article programs executed successfully.
Source locations checked:
- CS188 Textbook — Uninformed Search · Reopened§1.3.1 and tree-search conventions:deepest/LIFO,no cost guarantee,O(b^m) and O(bm). Article supplies explicit finite-graph duplicate-detection conditions rather than applying the page’s tree-search incompleteness claim to every DFS.
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · Read fixed-commit lines210–250 tree/graph DFS; freshly downloaded raw fixed commit and byte-compared prior copy,SHA25605180b631a702259d14bb2368b56a18f7b88f2e445629d64e5628d1cbe84ca3a. Original implementation uses iterator frames,not copied Node/frontier code.
Related topics