Python Snippet

Python DFS Templates (Recursive + Iterative)

Difficulty: Medium

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.

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

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.