TExcelTAD
Home › Data Structures & Algorithms › Cycle Detection

Cycle Detection

A cycle is a path that leads back to where it started. Detecting cycles matters in many places:

  • A build system or spreadsheet must refuse circular dependencies (A1 = B1 + 1, B1 = A1 * 2).
  • A database detects a deadlock as a cycle in its "waits for" graph.
  • A minimum spanning tree algorithm must avoid adding an edge that would close a cycle.

The method depends on whether the graph is undirected or directed.

Undirected graphs: DFS with a parent

During a DFS of an undirected graph, every edge leads either to a new vertex or back to one that is already visited. Going back to the vertex we just came from is not a cycle (it's the same edge in reverse). Reaching any other visited vertex means there are two different paths to it: a cycle.

python · try it yourself
def has_cycle_undirected(graph):
    visited = set()

    def dfs(u, parent):
        visited.add(u)
        for v in graph[u]:
            if v not in visited:
                if dfs(v, u):
                    return True
            elif v != parent:
                print(f"  edge {u}-{v} leads to visited {v}, not the parent: cycle")
                return True
        return False

    for start in graph:
        if start not in visited and dfs(start, None):
            return True
    return False

tree_like = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A"], "D": ["B"]}
with_loop = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"]}
print("tree_like:", has_cycle_undirected(tree_like))
print("with_loop:", has_cycle_undirected(with_loop))
tree_like: False
  edge C-A leads to visited A, not the parent: cycle
with_loop: True

Undirected graphs: union-find

Another approach processes the edges one at a time and keeps track of which vertices are already connected, using a union-find (disjoint set) structure. If an edge joins two vertices that are already in the same group, that edge closes a cycle. This is exactly the check Kruskal's algorithm uses.

python · try it yourself
def find(parent, x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]     # path halving keeps the trees flat
        x = parent[x]
    return x

def first_cycle_edge(vertices, edges):
    parent = {v: v for v in vertices}
    for u, v in edges:
        ru, rv = find(parent, u), find(parent, v)
        if ru == rv:
            return (u, v)
        parent[ru] = rv                   # union: merge the two groups
        print(f"join {u}-{v}")
    return None

edges = [("A", "B"), ("B", "D"), ("A", "C"), ("C", "D"), ("D", "E")]
print("closing edge:", first_cycle_edge("ABCDE", edges))
join A-B
join B-D
join A-C
closing edge: ('C', 'D')

Directed graphs: three colours

In a directed graph the parent trick is not enough. Consider A -> B, A -> C, C -> B: B is reached twice, but there is no cycle, because you can't go from B back to A. What matters is whether an edge points back to a vertex that is still on the current DFS path. DFS gives each vertex one of three states:

Colour Meaning
white not visited yet
grey on the current path (DFS has entered it but not finished)
black finished: all its descendants have been explored

An edge to a grey vertex is a back edge, and a back edge means a cycle.

python · try it yourself
WHITE, GREY, BLACK = 0, 1, 2

def find_cycle_directed(graph):
    colour = {v: WHITE for v in graph}
    path = []

    def dfs(u):
        colour[u] = GREY
        path.append(u)
        for v in graph[u]:
            if colour[v] == GREY:                  # back edge
                return path[path.index(v):] + [v]
            if colour[v] == WHITE:
                found = dfs(v)
                if found:
                    return found
        colour[u] = BLACK
        path.pop()
        return None

    for v in graph:
        if colour[v] == WHITE:
            found = dfs(v)
            if found:
                return found
    return None

diamond = {"A": ["B", "C"], "B": [], "C": ["B"]}
courses = {"A": ["B", "E"], "B": ["C"], "C": ["D"], "D": ["B"], "E": []}
print("diamond:", find_cycle_directed(diamond))
print("courses:", find_cycle_directed(courses))
diamond: None
courses: ['B', 'C', 'D', 'B']

The second graph has the cycle B → C → D → B, and the function returns it.

Directed graphs: Kahn's algorithm

A directed graph has no cycle exactly when it can be put in topological order (every edge points forward). Kahn's algorithm repeatedly removes a vertex with no incoming edges. If it gets stuck before all vertices are removed, the remaining vertices contain a cycle. The animation runs it on the courses graph from above:

python · try it yourself
def kahn(nodes, edges):
    indegree = {v: 0 for v in nodes}
    out = {v: [] for v in nodes}
    for u, v in edges:
        out[u].append(v)
        indegree[v] += 1
    ready = sorted(v for v in nodes if indegree[v] == 0)
    order = []
    while ready:
        u = ready.pop(0)
        order.append(u)
        for v in out[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                ready.append(v)
        ready.sort()
    if len(order) < len(nodes):
        stuck = [v for v in nodes if v not in order]
        return f"cycle detected: only {order} could be ordered, stuck on {stuck}"
    return f"order: {order}"

edges = [("A", "B"), ("A", "E"), ("B", "C"), ("C", "D"), ("D", "B")]
print(kahn("ABCDE", edges))
print(kahn("ABCDE", [e for e in edges if e != ("D", "B")]))
cycle detected: only ['A', 'E'] could be ordered, stuck on ['B', 'C', 'D']
order: ['A', 'B', 'C', 'D', 'E']

With the edge D -> B removed, the graph becomes a DAG and gets a full order. The Topological Sort lesson covers this algorithm in detail.

Summary

Graph Method Time
Undirected DFS, ignoring the edge back to the parent O(V + E)
Undirected union-find over the edges almost O(E)
Directed DFS with white/grey/black colours O(V + E)
Directed Kahn's algorithm (topological sort fails) O(V + E)

Test yourself

In an undirected DFS, why is an edge back to the parent not a cycle?

  1. Parents are never visited
  2. It is the same edge you just used, travelled in reverse
  3. Undirected graphs can't have cycles
  4. DFS skips parents automatically

In the three-colour DFS of a directed graph, which edge indicates a cycle?

  1. An edge to a white vertex
  2. An edge to a grey vertex
  3. An edge to a black vertex
  4. Any edge to a visited vertex

How does Kahn's algorithm reveal a cycle?

  1. It visits a vertex twice
  2. It runs out of vertices with in-degree 0 before ordering all of them
  3. It produces a negative number
  4. It never terminates