DFS
Depth-first search (DFS) walks a graph by going as deep as possible along one path before backtracking. It is implemented with recursion or an explicit stack, and it is the usual engine for backtracking and cycle detection.
Detailed Explanation
From a start node, DFS picks a neighbour, visits it fully, then tries the next neighbour. The order is not by distance. The first time you reach a node is not a shortest path. Use BFS for that.
The recursive form is three or four lines and uses the call stack as the path. The iterative form uses a list as a stack; you push neighbours in reverse if you want the same order as recursion. Both need a seen set on graphs with cycles. On trees you can skip seen if you never walk the parent, but a "tree" from a user is a graph until you prove otherwise.
Colouring nodes (white / grey / black) detects cycles in directed graphs: a grey neighbour is a back edge. In undirected graphs a neighbour that is seen and is not the parent is a cycle.
DFS finishing times produce a topological order on a DAG: append a node after its children, then reverse. Strongly connected components (Kosaraju, Tarjan) are DFS plus extra bookkeeping.
Recursion depth is the path length. A chain of 2000 nodes raises RecursionError. Rewrite with an explicit stack, or raise the limit only when the depth is bounded and trusted.
Backtracking is DFS that undoes a choice: place a queen, recurse, remove the queen. The stack (or the mutated board) is the current path.
Code Examples
def dfs(graph: dict[str, list[str]], start: str) -> list[str]:
seen: set[str] = set()
order: list[str] = []
def visit(node: str) -> None:
seen.add(node)
order.append(node)
for nxt in graph.get(node, []):
if nxt not in seen:
visit(nxt)
visit(start)
return order
g = {"a": ["b", "c"], "b": ["d"], "c": [], "d": []}
print(dfs(g, "a")) # ['a', 'b', 'd', 'c']def dfs_iter(graph: dict[str, list[str]], start: str) -> list[str]:
seen = {start}
stack = [start]
order = []
while stack:
node = stack.pop()
order.append(node)
for nxt in reversed(graph.get(node, [])):
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return orderCommon Gotchas
No `seen` set on a cyclic graph
infinite recursion or an infinite stack loop.
Using DFS for unweighted shortest paths
the first hit is not the nearest. Use BFS.
Recursion limit
deep graphs need an explicit stack.
Marking seen at push vs at pop changes order slightly
be consistent, and do not push duplicates if you mark at push.