DrawCode Algorithm Visualizer • Graph • Easy

Depth-First Search (DFS)

Tags: Graph, Traversal, Stack, Recursion, Backtracking

1. One-Liner

DFS follows one path as deep as possible before backtracking, using a stack (explicit or recursion).


2. The Problem It Solves

You need to traverse all reachable vertices, detect cycles, find connected components, run topological sort (on DAGs), solve mazes, or enumerate paths — DFS is the default deep exploration tool.


3. The Core Idea

Walk a maze while keeping a string on your hand: go forward until dead end, then rewind to the last junction and try another tunnel. The call stack (or explicit stack) remembers that path.


4. How It Works (Step-by-Step)

StepAction
1Mark current vertex visited
2For each unvisited neighbor: recursively DFS (or push on stack)
3When no new neighbors: backtrack (return or pop)
4Colors/timestamps (white/gray/black) detect cycles in directed graphs
5Postorder on DAG yields reverse topological order

5. Dry Run Example

Tree edges: 0→1, 0→2, 1→3. DFS from 0 visiting smaller id first: go 0→1→3, backtrack to 1, done, back to 0, go 2. Order: 0,1,3,2. If you need preorder, record on entry; postorder on exit.


6. Key Properties

PropertyDetail
Shortest path (unweighted)Not guaranteed — use BFS
MemoryO(h) recursion depth; O(V) worst case
Cycle detectionBack edge to gray vertex (directed)
Topological sortFinish times decreasing on DAG

7. Where It Is Used

Company / SystemUse
Garbage collectorsMark phase traces reachable objects
IDE / GitDependency and folder tree walks
CompilersCFG analysis, some register allocation contexts
Puzzle gamesMaze generation (e.g., randomized DFS)

8. Interview Tips

Know iterative vs recursive, time O(V+E), stack overflow risk on deep graphs, tree edge / back edge / cross edge classification. Follow-ups: find all paths, strongly connected components setup.


9. Comparison with Other Algorithms

DFSBFS
Data structureStackQueue
Unweighted shortest pathNoYes
Memory narrow treesO(depth)O(frontier)
Topological sortNatural on DAGAwkward

10. Complexity

----
TimeO(V + E)
SpaceO(V) visited + O(depth) recursion stack

Implementation Example (PYTHON)

def dfs(adj, s):
    n = len(adj)
    vis = [False] * n
    out = []
    def rec(u):
        vis[u] = True
        out.append(u)
        for v in adj[u]:
            if not vis[v]:
                rec(v)
    rec(s)
    return out

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer