liveBook · Manning

Acyclic graph

As explained in Grokking Data Structures

An acyclic graph is a graph that contains no cycles.

An acyclic graph is a graph with no cycles. A cycle is a path that starts and ends at the same vertex, so an acyclic graph never allows you to follow edges and return to where you began. section 13.5

A follower graph

Imagine directed follower relationships among animals. Giraffe→Crocodile→Monkey→Giraffe forms a cycle, so that graph is not acyclic. Removing every route that eventually returns to its starting vertex produces an acyclic graph. section 13.5

Use depth-first search (DFS) to check whether a directed graph is acyclic:

  • Mark each vertex white before exploration. section 13.14
  • Mark a vertex gray while exploring its outgoing edges, then black after all those edges have been processed. section 13.14
  • Finding a gray vertex again reveals a cycle; if no gray vertex is encountered, the graph is acyclic. 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

The iterative DFS implementation uses a stack, gray and black markers, and an acyclic flag to detect cycles. section 13.14

How Grokking Data Structures covers it

How deep it goes
Defines paths and cycles, then gives a colored-vertex DFS procedure; defers other applications to advanced treatment.
Examples
Uses an animal follower graph and an iterative stack-based DFS implementation with white, gray, and black vertex states.
What it assumes
Introduces paths, cycles, directed edges, and graph terminology before applying DFS.
What you can do after
Diagnose cycles in a directed graph using depth-first search and vertex-color tracking.
How it connects
Connects acyclic graphs with graphs, directed graphs, cycles, depth-first search, trees, and topological sorting.

Also explained in

Compare how 3 books explain acyclic graph →

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.