Code Snippets
/

Python DFS Templates (Recursive + Iterative)

Python DFS Templates (Recursive + Iterative)

DFS visits a graph by going as deep as possible before backtracking. Python lets you write it recursively (concise, but bounded by `sys.getrecursionlimit()`) or iteratively with an explicit stack (uglier, but safe for deep graphs). This entry ships both templates and a third variant that detects cycles in a directed graph using gray / black coloring.

Python
Medium
3 snippets
dfs
graphs
code-template
recursion

775 views

25

from collections import defaultdict

def dfs_recursive(graph, start):
    """Pre-order DFS via recursion. Returns the visit order."""
    visited = set()
    order = []

    def visit(node):
        if node in visited:
            return
        visited.add(node)
        order.append(node)
        for nbr in graph[node]:
            visit(nbr)

    visit(start)
    return order

graph = defaultdict(list)
for u, v in [(1, 2), (1, 3), (2, 4), (3, 4), (4, 5)]:
    graph[u].append(v)
    graph[v].append(u)

print(dfs_recursive(graph, 1))  # e.g. [1, 2, 4, 3, 5]

# Single node, no edges.
solo = defaultdict(list)
solo[7] = []
print(dfs_recursive(solo, 7))   # [7]

Recursive DFS reads top-to-bottom: visit the node, mark it, recurse into each neighbor. The closure pattern (visit defined inside dfs_recursive) keeps visited and order out of the public signature. The function is post-order if you append to order AFTER the recursive call instead of before. The only risk is Python's default recursion limit of 1000 frames: deep chains (linked-list-shaped graphs, long paths) crash with RecursionError and you should switch to the iterative version below.