LOGBOOK

HELP

Quiz Entry - updated: 2026.11.30

Why can a recursive DFS fail on a large graph, and how is it written without recursion?

The recursion goes as deep as the longest route DFS follows, which can be almost every vertex, for example on a long chain. Python stops at 1000 nested calls by default with a RecursionError, and Java throws a StackOverflowError once the thread's stack is full: with JDK 21 and its default 1 MB stack, a recursive DFS over a chain overflows after several thousand calls, between about 6 000 and 11 500 depending on how much each call keeps on the stack. An explicit stack in place of the call stack removes the limit.

def dfs_iterative(graph, s, visited):
    visited.add(s)
    stack = [(s, iter(graph.incident_edges(s)))]
    while stack:
        v, edges = stack[-1]
        for e in edges:                        # resume v's loop where it stopped
            w = graph.opposite(v, e)
            if w not in visited:
                visited.add(w)                 # e is a discovery edge
                stack.append((w, iter(graph.incident_edges(w))))
                break                          # go deeper first
        else:
            stack.pop()                        # v has no edges left: back up

How deep Java gets depends on the stack size, on the size of each frame and on whether the JIT compiler has compiled the method yet. The default thread stack is 1 MB on x64 Linux and macOS and 2 MB on their ARM versions, and it can be raised with -Xss. Measured with JDK 21 on x64 Linux and the default 1 MB stack, a recursive DFS over a chain of vertices, with its labels in a hash map, overflowed after about 6 100 nested calls once compiled and after about 7 900 in the interpreter; a leaner DFS, with its labels in a boolean array and its neighbours in array lists, got to about 11 500; an empty recursive method got further, to about 10 000 interpreted and 16 000 to 19 000 compiled. Graphs with millions of vertices are common, so the limit matters in practice.

The explicit stack lives on the heap, which is far larger and grows as needed. Each stack entry stands for one open call: the vertex and an iterator that remembers how far the loop over its incident edges has got. Pushing an entry is the recursive call, popping it is the return, and the vertices are visited in exactly the order of the recursive version.

A tempting shortcut is BFS with a stack in place of the queue, pushing all unvisited neighbours at once and marking them on the way in. That also visits every vertex in $O(n + m)$, but its tree is in general not a DFS tree: in a triangle A, B, C it pushes both B and C from A, so the edge B–C ends up joining two branches, which DFS never allows. Marking a vertex only when it is popped, and skipping it if it is already marked, restores depth-first behaviour.

Go deeper:

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 30, 2026