Sub topic 2
What Counts as a Cycle
This chapter assumes you know basic Python, the terms vertex and edge, and the difference between directed and undirected graphs. Before you can detect a cycle, you need an exact definition of one. Otherwise an algorithm can report cycles that are not there, or miss real ones. Most bugs in this area come from vague definitions, so this chapter fixes the rules that every later algorithm relies on.
Walks, Paths, and Cycles
A walk is a sequence of vertices v0, v1, ..., vk where each consecutive pair is joined by an edge. A walk is closed if v0 == vk. A cycle is a closed walk of length k >= 1 with two restrictions:
- No edge is used twice.
- No vertex repeats, except that the first and last vertex are the same.
Some texts call this a simple cycle. In this tutorial, "cycle" always means a simple cycle.
Undirected Graphs
In an undirected graph, the rule that no edge is used twice carries most of the weight. Going from A to B and straight back over the same edge forms a closed walk, but that walk is not a cycle. This is why a single edge A — B does not make a graph cyclic.
In a simple graph, which has no self-loops and no parallel edges, the shortest possible cycle has three vertices, such as a triangle. Multigraphs allow shorter ones:
- A self-loop is an edge from a vertex to itself, like
A — A. It is a cycle of length 1. - Two parallel edges between
AandBform a cycle of length 2. You leave on one edge and come back on the other.
Since edges, not vertices, are what may not repeat, an implementation has to tell edges apart. Tracking edge identities, rather than just "the vertex I came from," is the detail that a later chapter turns into working code.
Directed Graphs
In a directed graph, a cycle has to follow edge directions. The rule against reusing an edge is easy to satisfy here, because going back the way you came would need a second edge pointing the other way. That gives two results:
A → Btogether withB → Ais a cycle of length 2, even in a simple directed graph.- A self-loop
A → Ais a cycle of length 1.
A common mistake is to ignore direction. In the diagram below, the edges connect the same three vertices in a triangle in both graphs. The undirected graph has a cycle. The directed graph has none, because no path leads from C back to A. A directed graph with no cycles is a DAG (directed acyclic graph).
Summary of the Rules
| Structure | Undirected | Directed |
|---|---|---|
| Single edge between A and B | Not a cycle | Not a cycle |
| Self-loop on A | Cycle, length 1 | Cycle, length 1 |
| Two edges between A and B | Cycle, length 2 (parallel edges) | Cycle only if they point opposite ways |
| Triangle A, B, C | Cycle, length 3 | Cycle only if the directions go all the way around |
Checking a Candidate Cycle
The function below turns the definition into code. It takes an edge list, a vertex sequence, and the IDs of the edges used between consecutive vertices. It returns whether they form a cycle.
def is_cycle(edges, vertices, edge_ids, directed):
k = len(edge_ids)
if k == 0 or len(vertices) != k + 1 or vertices[0] != vertices[-1]:
return False
if len(set(edge_ids)) != k or len(set(vertices[:-1])) != k:
return False
for i, eid in enumerate(edge_ids):
a, b = edges[eid]
x, y = vertices[i], vertices[i + 1]
if (a, b) != (x, y) and (directed or (b, a) != (x, y)):
return False
return True
print(is_cycle([(0, 1)], [0, 1, 0], [0, 0], directed=False)) # False: edge reused
print(is_cycle([(0, 1), (0, 1)], [0, 1, 0], [0, 1], directed=False)) # True: parallel edges
print(is_cycle([(2, 2)], [2, 2], [0], directed=True)) # True: self-loop
print(is_cycle([(0, 1), (1, 2), (0, 2)], [0, 1, 2, 0], [0, 1, 2], directed=True)) # False
print(is_cycle([(0, 1), (1, 2), (0, 2)], [0, 1, 2, 0], [0, 1, 2], directed=False)) # TrueExercise
A directed graph has edges 1 → 2, 2 → 3, 3 → 1, and 3 → 4. Which vertices lie on a cycle, and does the graph stay cyclic if you treat every edge as undirected?
Show answer
Vertices 1, 2, and 3 lie on the cycle 1 → 2 → 3 → 1. Vertex 4 is reachable from the cycle but not on it. As an undirected graph it is still cyclic, because the triangle 1, 2, 3 remains a cycle.
Exercise
An undirected graph has exactly one edge, A — B. Why is the walk A, B, A not a cycle, and what single change would make the graph cyclic?
Show answer
The walk uses the same edge twice, which the definition forbids. Adding a second, parallel edge between A and B, or a self-loop on either vertex, would create a cycle.