Sub topic 2
What Counts as a Cycle
Every algorithm in this tutorial answers one question: does this graph contain a cycle? You can only judge whether an algorithm is correct if "cycle" has a precise meaning. Two things decide what counts as a cycle: whether edges have a direction, and whether the graph allows self-loops and parallel edges.
This chapter assumes you know basic Python, the words vertex, edge, directed and undirected, and the adjacency list and edge list representations from the previous chapter.
Walks, Paths, and Cycles
The definitions build on each other, so start with the loosest one.
- A walk is a sequence of vertices and edges,
v0, e1, v1, e2, ..., ek, vk, where each edgeeiconnectsv(i-1)tovi. Vertices and edges may repeat. - A closed walk is a walk that ends where it started (
vk == v0) and has at least one edge. - A path is a walk with no repeated vertices.
- A cycle is a closed walk of length
k >= 1that repeats no edge and no vertex, except that the first vertex is also the last.
The length of a cycle is its number of edges. Cycles have no fixed starting point. The rotations a, b, c, a and b, c, a, b describe the same cycle. In an undirected graph, the reversal a, c, b, a is also the same cycle.
A graph with no cycles is acyclic. An acyclic undirected graph is a forest, and a connected forest is a tree. An acyclic directed graph is a directed acyclic graph, or DAG.
Cycles in Undirected Graphs
In an undirected graph, an edge {u, v} can be traversed in either direction. That freedom is why the "no repeated edge" rule is essential. Without it, the walk u, v, u would count as a cycle, and every graph with at least one edge would be cyclic.
In a simple graph, meaning no self-loops and no parallel edges, the shortest possible cycle has three vertices, a triangle. Multigraphs, which allow both, have shorter ones:
- A self-loop is an edge from a vertex to itself. The walk
u, e, uuses one edge once and returns to its start, so it is a cycle of length 1. - Two parallel edges
e1ande2betweenuandvform the cycleu, e1, v, e2, uof length 2. It uses two distinct edges, so the rule is satisfied.
The parallel-edge case shows that a cycle is really defined by its edges, not by its vertex list. The vertex sequence u, v, u is a cycle when there are two edges between u and v, and not a cycle when there is only one. An algorithm that only remembers "I came from vertex u" cannot tell these two cases apart. That is why the undirected DFS in a later chapter tracks the edge it arrived by, not the parent vertex.
Undirected forests also have a counting test. A forest with V vertices and C connected components has exactly V - C edges. Any extra edge closes a cycle. This test tells you that a cycle exists without telling you where it is. It is also the idea behind union-find detection: an edge whose endpoints are already connected creates a cycle.
Cycles in Directed Graphs
In a directed graph, each edge (u, v) can only be followed from u to v. A directed cycle must follow every edge forward: v0 -> v1 -> ... -> vk = v0.
The direction rule changes which short structures count:
- A self-loop
(u, u)is a directed cycle of length 1. - The two edges
(u, v)and(v, u)are distinct edges, sou -> v -> uis a directed cycle of length 2. You do not need a multigraph for this. - Two parallel edges
(u, v)and(u, v)point the same way. They do not form a cycle, because you cannot get fromvback tou.
Direction also separates a directed graph from its underlying undirected graph, the graph you get by ignoring edge directions. Take the "diamond" with edges a -> b, a -> c, b -> d, c -> d. If you ignore directions, a, b, d, c, a is a cycle. With directions, there is no way back to a, so the graph is a DAG. This is the most common reason undirected techniques fail on directed graphs. Reaching an already-visited vertex d by a second route does not mean you have found a cycle.
A directed graph is acyclic exactly when it has a topological order, meaning an ordering of the vertices where every edge points from an earlier vertex to a later one. Kahn's algorithm, covered later, relies on this equivalence.
Summary of Cases
| Structure | Undirected graph | Directed graph |
|---|---|---|
| Self-loop on `u` | Cycle, length 1 | Cycle, length 1 |
| One edge between `u` and `v` | Not a cycle | Not a cycle |
| Two parallel edges `u`–`v` | Cycle, length 2 | Not a cycle if both point the same way |
| Edges `(u, v)` and `(v, u)` | Same as two parallel edges: cycle | Cycle, length 2 |
| Diamond `a-b, a-c, b-d, c-d` | Cycle, length 4 | Acyclic if all edges point away from `a` |
| Shortest cycle in a simple graph | 3 | 2 (or 1 if self-loops are allowed) |
Closed Walks Hide Cycles
Detection algorithms rarely trace a clean cycle directly. They notice a return: a walk that comes back to a vertex it has already used. The following facts explain why noticing a return is enough.
- Directed: every closed walk contains a directed cycle. Take the first vertex that repeats along the walk. The stretch between its two visits is a directed cycle.
- Undirected: every closed walk that repeats no edge contains a cycle. A closed walk that repeats edges may contain none, as
u, v, uover a single edge shows.
The difference between these two facts explains the design of the algorithms that follow. Directed DFS can report a cycle as soon as it reaches a vertex that is still on the current path. Undirected DFS has to make sure the "return" did not happen by walking back along the edge it just used.
Checking a Proposed Cycle in Code
The definitions turn directly into checkers. Each function below takes an edge list and a sequence of edge ids, which are indexes into that list. Using ids instead of vertices is what lets the checkers handle parallel edges correctly.
def is_undirected_cycle(edges, start, edge_ids):
"""True if edge_ids, walked from start, form a cycle in an undirected multigraph."""
if not edge_ids or len(set(edge_ids)) != len(edge_ids):
return False # empty, or an edge is reused
seen = {start}
cur = start
for k, eid in enumerate(edge_ids):
u, v = edges[eid]
if cur == u:
nxt = v
elif cur == v:
nxt = u
else:
return False # edge does not touch the current vertex
if k == len(edge_ids) - 1:
return nxt == start # must close the loop
if nxt in seen:
return False # inner vertex repeated
seen.add(nxt)
cur = nxt
def is_directed_cycle(edges, edge_ids):
"""True if edge_ids form a directed cycle, following each edge tail to head."""
if not edge_ids or len(set(edge_ids)) != len(edge_ids):
return False
start = edges[edge_ids[0]][0]
seen = {start}
cur = start
for k, eid in enumerate(edge_ids):
u, v = edges[eid]
if u != cur:
return False # edge does not leave the current vertex
if k == len(edge_ids) - 1:
return v == start
if v in seen:
return False
seen.add(v)
cur = v
# Undirected examples
und = [(0, 0), (1, 2), (1, 2), (3, 4), (4, 5), (5, 3)]
print(is_undirected_cycle(und, 0, [0])) # True: self-loop
print(is_undirected_cycle(und, 1, [1, 2])) # True: two parallel edges
print(is_undirected_cycle(und, 1, [1, 1])) # False: same edge twice
print(is_undirected_cycle(und, 3, [3, 4, 5])) # True: triangle
# Directed examples
dag = [(0, 1), (0, 2), (1, 3), (2, 3)] # diamond
print(is_directed_cycle(dag, [0, 2])) # False: 0->1->3 does not return
two = [(0, 1), (1, 0), (0, 1)]
print(is_directed_cycle(two, [0, 1])) # True: 0->1->0
print(is_directed_cycle(two, [0, 2])) # False: parallel, same directionThese checkers verify a cycle you already have. They do not search for one. Use them in tests: when a later algorithm returns a cycle, pass it to the matching checker to confirm the result.
Exercises
Exercise
An undirected graph has vertices 0 to 4 and edges {0,1}, {1,2}, {3,4}, {3,4}. Does it contain a cycle? If so, give its length.
Show answer
Yes. The two parallel edges between 3 and 4 form a cycle of length 2. The component {0, 1, 2} is a path and has no cycle. As a check, a forest with 5 vertices and 2 components would have 3 edges, and this graph has 4.
Exercise
A directed graph has edges a->b, b->c, a->c. Its underlying undirected graph is a triangle. Is the directed graph cyclic?
Show answer
No. No edge leads back to a, and the only edge out of b goes to c, which has no outgoing edges. The order a, b, c is a topological order, so the graph is a DAG, even though ignoring directions gives a cycle.
Exercise
Why does isundirectedcycle(und, 1, [1, 1]) return False while isundirectedcycle(und, 1, [1, 2]) returns True, even though both trace the vertices 1, 2, 1?
Show answer
The first sequence uses edge 1 twice, which the definition forbids, so it is a walk back along the same edge. The second uses edges 1 and 2, which are distinct parallel edges, so it is a cycle of length 2. A cycle is identified by its edges, not only its vertices.
Exercise
Prove that every closed walk in a directed graph contains a directed cycle.
Show answer
Let the closed walk be v0, v1, ..., vk with vk = v0 and k >= 1. At least one vertex repeats, because v0 appears at both ends. Choose the smallest j such that vj equals some earlier vi with i < j. Then vi, ..., vj repeats no vertex except vi = vj, and every step follows an edge forward. So it is a directed cycle. If j = i + 1, it is a self-loop.