Depth-First Search (DFS)

DFS explores as deep as possible along each branch using recursion or an explicit stack before backtracking. Standard graph traversal visits each vertex and edge once, taking O(V+E) time with an adjacency list.

One-Sentence Definition

DFS explores as far as possible along a single path using recursion or an explicit stack before backtracking to explore other branches. Standard graph traversal visits every vertex and edge once, running in O(V+E) time with an adjacency list.

Why It Matters

  • Forms the foundation for core graph problems such as cycle detection, topological sorting, connected components, and island counting.
  • Backtracking: generating permutations, combinations, Sudoku solutions, and N-Queens placements is essentially running DFS over a decision tree.
  • Pre-order, in-order, and post-order tree traversals are all forms of DFS (see k2.ds.tree).

Operating Boundaries

Backtracking tasks such as enumerating all permutations perform DFS over a much larger decision tree, so the linear time bound of basic graph traversal no longer applies. Moreover, three-color cycle detection for directed graphs differs from the parent-edge exclusion rule used in undirected graphs.

How It Works / Diagram

Example graph: A→B, A→C, B→D, C→D, C→E, D→F.

Figure 1

Visitation order: A → B → D → F (bottoms out) → backtracks to A → C → E (D is already visited and skipped).

Three-color cycle detection (directed graphs): White = unvisited, Gray = currently visiting (on the active recursion path), Black = completed. Encountering a Gray vertex during DFS means an edge points back to the current active path, confirming a directed cycle.

BFS DFS
Data Structure Queue Stack / Recursion
Traversal Order Level by level Plunge down one path first
Unweighted Shortest Path Guaranteed Not guaranteed
Memory Usage Large on wide graphs Large on deep graphs (deep recursion)
Typical Use Cases Shortest path, level-order expansion Cycle detection, topological sort, backtracking, connectivity

Runnable Example

Recursive and explicit-stack DFS, three-color cycle detection, grid island counting, and backtracking permutation generation (verified run log on Python 3.15.0):

# File: examples/23_dfs.py
# Depth-First Search (DFS): plunge down one path before backtracking (recursion / stack). Used for connectivity, cycle detection, and backtracking search.
import sys
sys.setrecursionlimit(10_000)

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": [], "F": []}
order = []
def dfs(u, seen=None):
    seen = seen if seen is not None else set()
    seen.add(u); order.append(u)
    for v in graph[u]:
        if v not in seen: dfs(v, seen)
dfs("A"); print("Recursive DFS visit order:", order)

def dfs_iter(start):
    seen, stack, out = set(), [start], []
    while stack:
        u = stack.pop()
        if u in seen: continue
        seen.add(u); out.append(u)
        stack.extend(reversed(graph[u]))      # Push in reverse order to match recursive traversal order
    return out
print("Explicit-stack DFS visit order:", dfs_iter("A"))

# Directed graph cycle detection (three-color marking): is there a circular dependency?
def has_cycle(g):
    WHITE, GRAY, BLACK = 0, 1, 2
    color = {u: WHITE for u in g}
    def visit(u):
        color[u] = GRAY
        for v in g[u]:
            if color[v] == GRAY or (color[v] == WHITE and visit(v)): return True
        color[u] = BLACK; return False
    return any(color[u] == WHITE and visit(u) for u in g)
print("graph has cycle:", has_cycle(graph), "| after adding F->A has cycle:", has_cycle({**graph, "F": ["A"]}))

# Number of islands (connected components)
sea = ["11000", "11010", "00100", "00011"]
seen = set()
def flood(r, c):
    if not (0 <= r < len(sea) and 0 <= c < len(sea[0])) or sea[r][c] == "0" or (r, c) in seen: return
    seen.add((r, c)); [flood(r+dr, c+dc) for dr, dc in ((1,0),(-1,0),(0,1),(0,-1))]
islands = 0
for r in range(len(sea)):
    for c in range(len(sea[0])):
        if sea[r][c] == "1" and (r, c) not in seen: flood(r, c); islands += 1
print("Number of islands:", islands)

# Backtracking: full permutations (classic DFS application)
def permutations(items, path=()):
    if not items: yield path; return
    for i, x in enumerate(items): yield from permutations(items[:i] + items[i+1:], path + (x,))
print("Permutations of abc:", ["".join(p) for p in permutations("abc")])

Recorded output:

Recursive DFS visit order: ['A', 'B', 'D', 'F', 'C', 'E']
Explicit-stack DFS visit order: ['A', 'B', 'D', 'F', 'C', 'E']
graph has cycle: False | after adding F->A has cycle: True
Number of islands: 4
Permutations of abc: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Both implementations produce the exact same visitation sequence (the explicit-stack version pushes neighbors in reverse order); adding the edge F→A causes the three-color check to detect a cycle.

Common Pitfalls

  • Using recursion on deep graphs: long node chains trigger RecursionError (see k2.ds.stack); switch to an explicit stack instead.
  • Forgetting to undo choices during backtracking: state mutations must be reverted when returning from a recursive call, otherwise branches pollute each other.
  • Applying three-color cycle detection to undirected graphs: in an undirected graph, the immediate parent vertex will be misidentified as a cycle unless you exclude the incoming parent edge or use Union-Find.
  • Assuming DFS finds the shortest path: the first path found by DFS is not guaranteed to be the shortest.

Connection to AI Development

  • Topological ordering of computation graphs: backpropagation traverses computation graphs in reverse topological order, commonly computed via post-order DFS (see k2.ds.graph).
  • Recursive processing of code and documents: traversing ASTs, directory trees, and nested JSON payloads.
  • Search-based reasoning: Tree of Thoughts explores reasoning branches using either BFS or DFS strategies. https://arxiv.org/abs/2305.10601
  • Constraint solving and planning: backtracking with pruning is a foundational solver technique for agent planning and scheduling tasks.

Further Reading

Concept Check

When using DFS to enumerate all permutations of n elements, is the time complexity still O(n)?

Reference answer: No. Generating the full output produces n! permutations, and each permutation requires recording n elements.

Verification & Reproduction

Verification date: 2026-10-14. Example status: passed. Run log for this batch: 23_dfs.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram