Python 3D Academyবাংলা

Depth-first search: exploring a maze

🌍 In real life. Exploring a cave or a maze, you don't check every first turning before going deeper. You pick a passage and follow it as far as it goes, leaving chalk marks so you never walk the same corridor twice. At a dead end you walk back to the last junction that still has an unexplored passage, and take that. The old trick of keeping one hand on the wall works the same way: it follows each passage to its end and comes back along the other side. In a maze with loops, though, the hand can lead you round a pillar forever; the chalk marks are what make the method work in any maze.

That is depth-first search. Where BFS spreads out in rings, DFS dives along one path and backs up only when it must. It doesn't find the fewest steps, but it is simple, written recursively it uses memory only for the current path, and is the base of many later algorithms: topological order and cycle finding (Chapter 52) are DFS with a little bookkeeping.

The idea in one sentence: DFS keeps the vertices still to try on a stack (or uses the call stack, by recursion): it takes the most recently added vertex, visits it if it is new, and adds its unvisited neighbours, so it always goes deeper before going wider.

Its words:

  • stack: last in, first out (Chapter 39); here, the passages still to try, the newest on top
  • visit: the moment a vertex is first reached and marked
  • backtrack: returning to an earlier vertex once a path has nothing new left
  • connected component: a group of vertices all reachable from each other, and from nothing outside the group

How it works, step by step, with a stack:

  1. push the start
  2. pop the top vertex v; if it was visited already, skip it
  3. otherwise visit v, and push its unvisited neighbours (in reverse, so the alphabetically first one is on top and is explored next)
  4. repeat until the stack is empty

Watch DFS dive from A: it goes A, B, D, then C, E, and backs up to reach F; C was pushed twice, so the second copy is skipped:

Why it is correct. Every vertex reachable from the start gets visited. Suppose some reachable vertex were never visited, and look at the first one on a path from the start. Its predecessor on that path was visited, and visiting it pushed every unvisited neighbour, including this one; the search only stops when the stack is empty, so this vertex was popped and visited, which is a contradiction. The seen check means each vertex is visited once, even when it is pushed more than once. With the reversed push, the stack version visits in the same order as the recursive one below: the first neighbour is always explored next.

What it costs, by counting. Each vertex is visited once and each edge looked at from both ends: O(V + E), the same as BFS. The stack can hold up to about E entries (a vertex may be pushed once per neighbour). The recursive version uses one call frame per vertex on the current path. On a long chain of 5,000 vertices that passes Python's limit of about 1,000 frames, so for big graphs use the explicit stack.

def dfs_order(graph, start):
    seen, order = set(), []
    stack = [start]
    while stack:
        v = stack.pop()
        if v in seen:
            continue                     # pushed twice: already visited
        seen.add(v)
        order.append(v)
        for w in reversed(graph[v]):     # so the first neighbour ends on top
            if w not in seen:
                stack.append(w)
    return order

towns = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"], "D": ["B", "C", "F"], "E": ["C"], "F": ["D"]}
print(dfs_order(towns, "A"))

# the same search with recursion: the call stack does the backtracking
def dfs(graph, v, seen, order):
    seen.add(v)
    order.append(v)
    for w in graph[v]:
        if w not in seen:
            dfs(graph, w, seen, order)   # go deeper before trying the next neighbour

order = []
dfs(towns, "A", set(), order)
print(order)

def count_components(graph):
    seen, groups = set(), 0
    for start in graph:
        if start in seen:
            continue
        groups += 1                      # a vertex no earlier search reached
        stack = [start]
        while stack:
            v = stack.pop()
            if v in seen:
                continue
            seen.add(v)
            stack.extend(w for w in graph[v] if w not in seen)
    return groups

print(count_components({"A": ["B"], "B": ["A"], "C": [], "D": ["E"], "E": ["D"]}))

Mistakes and edge cases.

  • no visited marks: on a cycle the search goes round forever (or until RecursionError)
  • skipping the "already visited" check after pop: with the stack version a vertex can be pushed by two neighbours; without the check it is visited twice
  • pushing neighbours in their own order: the last one pushed is popped first, so the search goes to the last neighbour first; reverse them to match the recursive order
  • counting components with one search: a single DFS only reaches its own component; start a new search from every vertex not yet seen
  • very deep recursion: use the explicit stack for long chains

Quiz

  1. What does this print?

    def dfs_order(graph, start):
        seen, order = set(), []
        stack = [start]
        while stack:
            v = stack.pop()
            if v in seen:
                continue                     # pushed twice: already visited
            seen.add(v)
            order.append(v)
            for w in reversed(graph[v]):     # so the first neighbour ends on top
                if w not in seen:
                    stack.append(w)
        return order
    
    graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A"], "D": ["B"]}
    print(dfs_order(graph, "A"))
  2. BFS or DFS: which one finds the fewest steps from the start to every vertex?

    • BFS: it reaches vertices in order of distance
    • DFS: it goes deeper, so it gets there sooner
    • Both, always
  3. This visits some vertices twice. After which line is a check missing?

    def dfs_order(graph, start):
        seen, order = set(), []
        stack = [start]
        while stack:
            v = stack.pop()
            seen.add(v)
            order.append(v)
            for w in reversed(graph[v]):
                if w not in seen:
                    stack.append(w)
        return order
  4. How many separate groups?

    def count_components(graph):
        seen, groups = set(), 0
        for start in graph:
            if start in seen:
                continue
            groups += 1                      # a vertex no earlier search reached
            stack = [start]
            while stack:
                v = stack.pop()
                if v in seen:
                    continue
                seen.add(v)
                stack.extend(w for w in graph[v] if w not in seen)
        return groups
    
    print(count_components({"A": ["B"], "B": ["A"], "C": [], "D": ["E"], "E": ["D"], "F": []}))
  5. Why use an explicit stack instead of recursion for DFS on a huge graph?

    • A long path would need more call frames than Python allows (about 1,000)
    • The explicit stack visits fewer vertices
    • Recursion can't do DFS

Coding tasks

  1. Write dfs_order(graph, start): the order in which DFS visits the vertices, always exploring a vertex's neighbours in the order they are listed (the first neighbour first). Use a stack, or recursion.

  2. Write count_components(graph): how many separate groups (connected components) the undirected graph has. Every vertex is a key of graph, even one with no edges.