liveBook · Manning

Depth-first search

As explained in Grokking Data Structures

Depth-first search is a graph traversal algorithm that explores a path as deeply as possible before backtracking.

Depth-first search (DFS) traverses a graph by following one path as far as possible, then backtracking to try another available edge. Unlike breadth-first search (BFS), it does not explore outward in distance-based rings and cannot find shortest paths. section 13.14 section 13.16

DFS supports several graph-analysis tasks:

Detecting cycles with vertex colors

Mark every vertex white initially. When DFS visits a vertex, mark it gray, push its outgoing neighbors, and later mark it black after those edges are explored. Encountering a gray vertex indicates a cycle. section 13.14

def dfs(self, start_vertex, color=None):
    if color is None:
        color = {v: 'white' for v in self._adj}
    acyclic = True
    stack = Stack()
    stack.push((False, start_vertex))
    while not stack.is_empty():
        (mark_as_black, v) = stack.pop()
        col = color.get(v, 'white')
        if mark_as_black:
            color[v] = 'black'
        elif col == 'grey':
            acyclic = False
        elif col == 'white':
            color[v] = 'grey'
            stack.push((True, v))
            for (_, w) in self._get_vertex(v).outgoing_edges():
                stack.push((False, w))
    return acyclic, color

An iterative Python implementation uses a stack of vertices and return markers, tracks white, gray, and black states, and reports whether the graph is acyclic. section 13.14

How Grokking Data Structures covers it

How deep it goes
Explains stack-based traversal, backtracking, vertex colors, and cycle detection, but defers other major applications.
Examples
Demonstrates white, gray, and black vertex states and an iterative stack implementation that inspects outgoing edges.
What it assumes
Assumes graphs with vertices and edges, following graph representation and breadth-first traversal.
What you can do after
Build it from scratch by using a stack, vertex colors, and outgoing-edge traversal to detect cycles.
How it connects
Connects graphs, breadth-first search, stacks, directed graphs, cycles, connected components, and directed acyclic graphs.

Also explained in

Compare how 7 books explain depth-first search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.