liveBook · Manning

Cycle

As explained in Grokking Data Structures

A cycle is a path in a graph that starts and ends at the same vertex.

A cycle is a path in a graph that starts and ends at the same vertex. Following its edges eventually brings you back to where you began. section 13.5

Recognize cycles by checking these related ideas:

  • A path is an ordered sequence of connected edges that lets you travel from one vertex to another. section 13.5
  • A graph with at least one cycle is cyclic; a graph with no cycles is acyclic. section 13.16 section 13.5
  • A loop is a special edge whose source and destination are the same vertex; it is distinct from a longer cycle. section 13.2
  • Trees are acyclic graphs, so no path from a tree's root to a leaf visits the same node twice. section 11.2

A follower cycle

Suppose Giraffe follows Crocodile, Crocodile follows Monkey, and Monkey follows Giraffe. The path Giraffe→Crocodile→Monkey→Giraffe returns to its starting vertex, so it forms a cycle. Monkey↔Giraffe also forms a smaller cycle. section 13.5

Depth-first search can detect cycles in a directed graph. Mark unvisited vertices white, active vertices gray, and completed vertices black. Discovering a gray vertex means the search has reached a vertex still on the current path, revealing 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

Inspect an iterative DFS implementation that uses a stack, gray and black colors, and an acyclic result. section 13.14

How Grokking Data Structures covers it

How deep it goes
Defines cycles through paths, distinguishes loops, and explains DFS color states for detecting them.
Examples
Uses a follower graph involving Giraffe, Crocodile, and Monkey to show both longer and smaller cycles.
What it assumes
Assumes vertices, edges, paths, and graph traversal while defining cycles and related terms in plain language.
What you can do after
Diagnose/debug with it by recognizing cycles and applying DFS color marking to test graph acyclicity.
How it connects
Connects cycles with graphs, paths, directed graphs, acyclic graphs, depth-first search, and trees.

Also explained in

Compare how 5 books explain cycle →

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.