← Back to Algorithms, page 4

algorithms-0065 · Easy fresher

Depth-first search on a graph: visit every node reachable from a start node, recursively and with an explicit stack, and count connected components.

DFS follows one neighbour as deep as possible before backtracking. Mark a node visited when it is first reached so cycles do not loop forever. Recursive and stack-based versions both run in O(V + E) time and O(V) space; the stack version avoids recursion limits. Starting a new DFS from each unvisited node counts connected components.

Full answer

Problem

Given an undirected graph as an adjacency list and a start node, return the nodes in DFS visiting order. Also count the connected components of the whole graph.

Example: {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []} from 0 visits [0, 1, 3, 2], and the graph has 2 components ({0, 1, 2, 3} and {4}).

Constraints: up to 10^5 nodes and edges; the graph may contain cycles and isolated nodes.

Brute force

Without a visited set, a recursive walk revisits nodes through every cycle and never terminates. Checking "visited" by scanning the output list works but costs O(V) per check, giving O(V^2 + E).

Optimal approach

Recursive: visit(u) marks u, records it, and calls visit(v) for each unvisited neighbour.

Iterative: push the start; pop u; skip if already seen; mark and record; push unvisited neighbours in reverse so the order matches the recursive version.

Components: loop over all nodes; each unvisited node starts a new DFS and increments the count.

Why it works

Every reachable node is eventually pushed, because DFS explores every edge out of every visited node. The visited set guarantees each node is processed once, so cycles terminate. In the component loop, one DFS marks exactly the nodes connected to its start, so each new start belongs to a component not yet counted.

Complexity

O(V + E) time: each node is processed once and each adjacency list scanned once. O(V) space for the visited set and the stack (or recursion depth).

Code

python
import random


def dfs_recursive(adj, start):
    order, seen = [], set()

    def visit(u):
        seen.add(u)                      # mark on entry so cycles terminate
        order.append(u)
        for v in adj[u]:
            if v not in seen:
                visit(v)
    visit(start)
    return order


def dfs_iterative(adj, start):
    """Explicit stack. Neighbours pushed in reverse so the visit order matches the recursive one."""
    order, seen, stack = [], set(), [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        for v in reversed(adj[u]):
            if v not in seen:
                stack.append(v)
    return order


def count_components(n, adj):
    seen, comps = set(), 0
    for s in range(n):
        if s not in seen:
            comps += 1
            stack = [s]
            seen.add(s)
            while stack:
                u = stack.pop()
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        stack.append(v)
    return comps


def has_path(adj, a, b):
    return b in set(dfs_iterative(adj, a))


def brute_components(n, edges):
    """Repeatedly merge labels until nothing changes."""
    label = list(range(n))
    changed = True
    while changed:
        changed = False
        for u, v in edges:
            m = min(label[u], label[v])
            if label[u] != m or label[v] != m:
                label[u] = label[v] = m
                changed = True
    return len(set(label))


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []}
    assert dfs_recursive(adj, 0) == dfs_iterative(adj, 0) == [0, 1, 3, 2]
    assert dfs_iterative(adj, 4) == [4]
    assert has_path(adj, 0, 3) and not has_path(adj, 0, 4)
    assert count_components(5, adj) == 2
    rng = random.Random(65)
    for _ in range(500):
        n = rng.randint(1, 12)
        edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 15))]
        g = {u: [] for u in range(n)}
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        assert count_components(n, g) == brute_components(n, edges)
        assert dfs_recursive(g, 0) == dfs_iterative(g, 0)
    print("all tests passed")

Save as b65_dfs.py and run python3 b65_dfs.py. It prints all tests passed (Python 3.13.5).

Edge cases

Start node with no edges. Self-loops and parallel edges. Disconnected graphs (single-start DFS misses other components). Deep paths with 10^5 nodes overflow Python's recursion limit, so use the stack version.

Pattern

Graph traversal with a visited set. DFS underlies connected components, cycle detection, topological sort, flood fill, path existence, bridges and articulation points, and backtracking over implicit graphs.

python
import random


def dfs_recursive(adj, start):
    order, seen = [], set()

    def visit(u):
        seen.add(u)                      # mark on entry so cycles terminate
        order.append(u)
        for v in adj[u]:
            if v not in seen:
                visit(v)
    visit(start)
    return order


def dfs_iterative(adj, start):
    """Explicit stack. Neighbours pushed in reverse so the visit order matches the recursive one."""
    order, seen, stack = [], set(), [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        for v in reversed(adj[u]):
            if v not in seen:
                stack.append(v)
    return order


def count_components(n, adj):
    seen, comps = set(), 0
    for s in range(n):
        if s not in seen:
            comps += 1
            stack = [s]
            seen.add(s)
            while stack:
                u = stack.pop()
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        stack.append(v)
    return comps


def has_path(adj, a, b):
    return b in set(dfs_iterative(adj, a))


def brute_components(n, edges):
    """Repeatedly merge labels until nothing changes."""
    label = list(range(n))
    changed = True
    while changed:
        changed = False
        for u, v in edges:
            m = min(label[u], label[v])
            if label[u] != m or label[v] != m:
                label[u] = label[v] = m
                changed = True
    return len(set(label))


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2], 4: []}
    assert dfs_recursive(adj, 0) == dfs_iterative(adj, 0) == [0, 1, 3, 2]
    assert dfs_iterative(adj, 4) == [4]
    assert has_path(adj, 0, 3) and not has_path(adj, 0, 4)
    assert count_components(5, adj) == 2
    rng = random.Random(65)
    for _ in range(500):
        n = rng.randint(1, 12)
        edges = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 15))]
        g = {u: [] for u in range(n)}
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        assert count_components(n, g) == brute_components(n, edges)
        assert dfs_recursive(g, 0) == dfs_iterative(g, 0)
    print("all tests passed")

Recursive and stack DFS with matching order, plus component counting cross-checked against a label-merging brute force.

Complexity

Time: O(V + E). Space: O(V). The iterative version may push a node several times before it is popped; the seen check on pop keeps processing to once per node.

By level

Fresher: Writes recursive DFS with a visited set and explains why cycles would otherwise loop. Counts components by starting DFS from each unvisited node.

Mid: Writes the stack version, explains marking on push versus pop, and states O(V + E). Uses DFS to find a path and to check reachability.

Senior: Discusses DFS on implicit or very large graphs, iterative deepening, and memory limits of the visited set. Relates DFS orderings (pre and post times) to cycle detection, topological sort and strongly connected components.

Key points

  • Mark visited to handle cycles
  • Recursive and stack versions are equivalent
  • Push neighbours in reverse to match recursive order
  • One DFS per unvisited node counts components
  • O(V + E)

Common mistakes

  • Marking visited too late and processing a node twice
  • No visited set at all on a cyclic graph
  • Using recursion on very deep graphs in Python
  • Only searching from one start on a disconnected graph

Follow-ups

  • How do you detect a cycle with DFS?
  • How would you find a path, not just reachability?
  • When would you prefer BFS over DFS?

Tips

  • Say where the visited mark happens
  • Mention recursion limits
  • Connect DFS to components and topological sort

Evaluation rubric

  • Correct traversal with visited set
  • Iterative version
  • Component count
  • Correct complexity