Detecting cycles: parent tracking and the recursion stack

Video lessonComing soon

1 Does the walk come back?

Some graph problems hang on one question: does a path lead back to where it started? That path is a cycle. If DSA needs Java first and Java needs DSA first, the two courses form a cycle, and no student can start either.

Picture the graph as a city map: junctions are vertices, and roads are edges. A walker explores it the way depth-first search (DFS) does. She takes a road to a new junction and keeps going, and when no new road is left, she walks back. She chalks every junction she reaches, as DFS marks visited.

The first idea is that a chalked junction means she has walked in a circle. That rule is wrong in both kinds of graph, and each fix is half of this lesson's title:

  • Two-way roads (undirected graphs). The road she came along always leads back to a chalked junction. The fix is to remember the parent.
  • One-way streets (directed graphs). A chalked junction can sit on a branch she has already finished. The fix is to remember the current path, the recursion stack.

2 Two-way roads: skip the parent

Take one road, 0 – 1. DFS walks from 0 to 1. The road goes both ways, so the list of 1 holds 0, which is visited. The first idea reports a cycle, but the walker only looked back down the road she came on.

So each call remembers its parent, the vertex it came from, and skips it. Any other visited neighbour is a real cycle. The search already reached that vertex one way, and this road is a second way in. On two-way roads, we can go along one way and come back along the other.

Here is a DFS on five vertices. Each call is dfs(vertex, parent), and the first call has parent −1. The boxes hold the parent each vertex was reached from. An empty box is a vertex not visited yet.

Finding a cycle with the parent check
01234
Bold: the current path
-101234
Start at 0. It has no parent

The path from 1 down to 3, and the road from 3 back to 1, make the cycle 1, 2, 4, 3, 1.

BFS can do the same check. Its queue holds pairs of a vertex and its parent. When we take a vertex out, a visited neighbour that is not its parent means a cycle.

It returns true on our graph, and false once the edge 3 – 4 is taken out, because the graph is then a tree.

3 One-way streets: visited is not enough

Now each road is one-way. Take the streets 0 → 1, 0 → 2, 1 → 3 and 2 → 3. DFS goes 0 → 1 → 3, walks back to 0, and goes to 2. The street from 2 leads to 3, which is visited, so the first idea reports a cycle. There is none. Vertex 3 only has two ways in.

The parent check does not help. 3 is not the parent of 2, so it still reports a cycle. It also misses real ones. In 0 → 1 → 0, the street back to 0 closes a cycle, but 0 is the parent of 1, so the check skips it.

0123
3 is reached twice, but nothing leads back
01
A real cycle through the parent

On two-way roads, two routes to one junction always make a loop. On one-way streets they do not, because we cannot walk a route backwards. A directed cycle needs a street back to a junction on the route we are walking right now.

4 Breadcrumbs on the current path

So the walker also carries breadcrumbs. She drops one on each junction as she walks in, and picks it up when she walks back out of it for good. At any moment, the breadcrumbs mark her route from the start to where she stands. In code, that route is the recursion stack: the dfs calls that have started and not yet returned.

A junction she has finished gets a flag instead. So each vertex is in one of three states, named by colour:

ColourThe vertex isReaching it means
whitenot visited yetgo into it
greyon the current patha cycle
blackfinishednothing new, skip it

A black vertex is safe to skip. Its search has already ended, and nothing it reaches leads back to the current path. If something did, its own search would have found the cycle first.

Here is the four-junction graph from above with three more streets: 2 → 4, 4 → 5 and 5 → 2.

Finding a cycle with three colours
0grey​1white2white3white4white5white
Filled and bold: the current path
dfs(0)top →
Start at 0. It turns grey

The grey vertices are always the calls on the stack. In step 4, vertex 3 is visited but black, so the search moves on. In step 6, the street 5 → 2 points into the stack, and 2 → 4 → 5 → 2 is the cycle.

5 The three-colour check in code

A vertex turns grey when its call starts and black just before its call returns. The loop in the middle follows the table: grey means a cycle, white means go in, and black is skipped.

It returns true on our six vertices, false without the street 5 → 2, and false on the diamond.

C++

state goes in by reference. The helper takes vector<int>& state, so every call colours the same array. Without the &, each call colours its own copy, and no call ever sees a grey vertex from another.

The array starts white. A new int[] is all zeros, and WHITE is 0, so no loop is needed to fill it.

About 1,000 calls deep. By default, Python stops a recursion at about 1,000 nested calls with a RecursionError. A long chain of vertices goes far deeper. sys.setrecursionlimit raises the limit.

A closure. dfs is defined inside hasCycle, so it reads adj and state without taking them as arguments.

Declare the closure first. dfs calls itself, so it is declared with var before it is assigned. A new slice of int is all zeros, which is white.

&mut for the colours. The helper takes state: &mut Vec<u8> so it can change the caller's array. In the undirected version, the parent is an Option<usize>, because a usize cannot be −1.

The array starts white. A new int[] is all zeros, and White is 0, so no loop is needed to fill it.

6 Every vertex, and the cost

The two checks differ in one rule and share everything else:

GraphA visited neighbour is a cycle whenWe keep
Undirectedit is not the parentvisited, and the parent per call
Directedit is greystate: white, grey or black
  • Start from every vertex. The cycle may sit where vertex 0 cannot reach. So hasCycle starts a search from every vertex not yet visited. A directed graph can hide a cycle even in one piece: with the streets 1 → 0, 1 → 2 and 2 → 1, a search from 0 goes nowhere.
  • Time. Each vertex is entered once, because a search only goes into unvisited vertices. Each edge is looked at once from its tail in a directed graph, and once from each end in an undirected one. So the whole check is O(V + E). At 10⁵ vertices and 2 × 10⁵ edges, that is a few hundred thousand steps.
  • Space. The array is O(V), and so is the call stack. On a chain 0 → 1 → … → 99999, the search goes 10⁵ calls deep. A stack that deep can overflow, and the program stops with a Runtime Error. A DFS with a stack of our own avoids that. So does Kahn's algorithm in the next lesson, which uses a queue.

7 Mistakes and edge cases

  • One visited array on a directed graph. On the diamond 0 → 1, 0 → 2, 1 → 3, 2 → 3, it reports a cycle. The answer is false.
  • Never turning a vertex black. A vertex left grey after its call returns looks like part of the path forever. The diamond fails the same way.
  • Skipping every visited neighbour. In an undirected graph, skipping all of them, not only the parent, never reports anything. On our five vertices it says false, but 1, 2, 4, 3 is a cycle.
  • Searching only from vertex 0. With vertex 0 alone and a triangle 1 – 2 – 3, the search from 0 sees nothing and says false.
  • Self-loops and parallel edges. An edge from v to v is a cycle, and both checks report it. Two edges between u and v are a cycle too. The parent check skips both at v, but back at u, the second edge meets v again.

8 When to look for a cycle

The sign is a question about whether a path can lead back to its start. It often comes in disguise:

  • Prerequisites or dependencies. Courses, build steps or tasks that wait on each other can all finish only when the directed graph has no cycle.
  • Is this a tree? An undirected graph is a tree when it is connected and has no cycle.
  • Which vertices are safe? A vertex is safe when no path from it reaches a cycle. The three colours can tell: a safe vertex is one whose search ends black.

A directed graph has a topological order exactly when it has no cycle. Kahn's algorithm, in the next lesson, finds cycles too. Union-find, a later lesson, finds them in undirected graphs one edge at a time. A linked list is the easy case. Each node has only one next, so fast and slow pointers find its cycle without any marks.

Before writing a cycle check, ask whether the edges go one way or both. Two-way roads need the parent, and one-way streets need the path.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.