algoritmauzmanı
Sign in
TREN
8.3Graph Applications
Lesson 8.3.2

Detecting a cycle

If a course is a prerequisite of another course that is in turn its own prerequisite, no student can ever start. If cells in a spreadsheet refer to each other in a circle, none of them can be computed. Both are cycles in a graph: you can leave a vertex, follow edges and come back to the same vertex. In this lesson you write a function that finds out with DFS whether there is a cycle; the same function works on directed and undirected graphs.

What you will learn
  • What it means to split vertices into three states: white, grey and black
  • Why a grey neighbour means a cycle and a black one does not
  • Why you must not count the edge you came by in an undirected graph
8 minTime O(V + E)Memory O(V)C · Java · Python

1Idea

The DFS keeps every vertex in one of three states. A white (0) vertex has not been seen yet. A grey (1) vertex has been entered but is not finished: it is on the path from the start to the current vertex, on the call stack. A black (2) vertex has had all its neighbours visited and its call has returned.

If a neighbour of a vertex is grey, that neighbour is on the current path: you came down from it, and now you found an edge from here back to it. The path and this form a cycle, and the function returns true at once. If the neighbour is black, everything below it was already visited and no cycle showed up there; reaching it by a second way is not a cycle. If the neighbour is white, you go down to it.

In an undirected graph every edge sits in two lists: v in the list of u and u in the list of v. If you came to v from u, the u in the list of v looks grey, but it is not a new edge, it is the edge you came by. That is why an undirected graph keeps the parent parameter and skips that neighbour. In a directed graph u→v and v→u are two separate edges, and together they really are a cycle; the parent is not skipped.

Since a graph can be in several pieces, hasCycle starts a new DFS from every white vertex, as in connected components.

In an undirected graph you never meet a black neighbour, so two colours are enough there: any visited neighbour other than the parent means a cycle. In a directed graph telling grey from black is essential; that difference is also the basis of topological sort.

2Step by step

The drawing shows a directed graph with 6 vertices. The text under a vertex is its colour; vertices with no text are white. Black vertices are drawn faded. The dfsCycle calls are shown under the drawing, the top one last.

012345
Call stack
  1. Start. Every vertex is white (0).
  2. 0 is white: dfsCycle(0) starts and 0 turns grey.
  3. The first neighbour of 0, 1, is white: go down to it, 1 turns grey.
  4. The only neighbour of 1, 3, is white: 3 turns grey.
  5. 3 has no neighbours. It is finished: it turns black and the call returns.
  6. 1 has no other neighbours: 1 turns black too.
  7. The second neighbour of 0, 2, is white: 2 turns grey.
  8. The first neighbour of 2, 3, is black. Everything below 3 was visited already; reaching it by a second way is not a cycle. Move on.
  9. The second neighbour of 2, 4, is white: 4 turns grey.
  10. The neighbour of 4, 5, is white: 5 turns grey. The path is now 0, 2, 4, 5.
  11. The neighbour of 5, 2, is grey: 2 is on the path. 5→2 is a back edge; the cycle 2→4→5→2 is found. true is returned.
  12. true is passed back through every call; hasCycle returns true.

#define MAX 8 struct Node {    int data;    struct Node* next;}; struct Graph {    int n;    bool directed;    struct Node* adj[MAX];}; bool dfsCycle(struct Graph* g, int u, int parent, int color[]) {    color[u] = 1;                             // grey: u is on the path    for (struct Node* p = g->adj[u]; p != NULL; p = p->next) {        int v = p->data;        if (!g->directed && v == parent) continue; // the edge you came by        if (color[v] == 1) return true;       // grey neighbour: a cycle        if (color[v] == 0 && dfsCycle(g, v, u, color)) return true;    }    color[u] = 2;                             // black: u is finished    return false;} bool hasCycle(struct Graph* g) {    int color[MAX] = {0};                     // 0 white: not seen    for (int u = 0; u < g->n; u++)        if (color[u] == 0 && dfsCycle(g, u, -1, color)) return true;    return false;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class ListGraph {    int n;    boolean directed;    Node[] adj;    ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; }} boolean dfsCycle(ListGraph g, int u, int parent, int[] color) {    color[u] = 1;                             // grey: u is on the path    for (Node p = g.adj[u]; p != null; p = p.next) {        int v = p.data;        if (!g.directed && v == parent) continue;  // the edge you came by        if (color[v] == 1) return true;       // grey neighbour: a cycle        if (color[v] == 0 && dfsCycle(g, v, u, color)) return true;    }    color[u] = 2;                             // black: u is finished    return false;} boolean hasCycle(ListGraph g) {    int[] color = new int[g.n];               // 0 white: not seen    for (int u = 0; u < g.n; u++)        if (color[u] == 0 && dfsCycle(g, u, -1, color)) return true;    return false;}
class Node:    def __init__(self, data):        self.data = data        self.next = None class ListGraph:    def __init__(self, n, directed=False):        self.n = n        self.directed = directed        self.adj = [None] * n def dfs_cycle(g, u, parent, color):    color[u] = 1                          # grey: u is on the path    p = g.adj[u]    while p is not None:        v = p.data        if not g.directed and v == parent:  # the edge you came by            p = p.next            continue        if color[v] == 1:                 # grey neighbour: a cycle            return True        if color[v] == 0 and dfs_cycle(g, v, u, color):            return True        p = p.next    color[u] = 2                          # black: u is finished    return False def has_cycle(g):    color = [0] * g.n                     # 0 white: not seen    for u in range(g.n):        if color[u] == 0 and dfs_cycle(g, u, -1, color):            return True    return False

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(V + E)

Every vertex turns grey once and black once; every adjacency list is read at most once: O(V + E).

Memory
O(V)

The color array holds V elements; in the worst case the recursion goes V levels deep.

The function returns as soon as it finds a cycle, so in a graph with a cycle it often does not need to visit the whole graph. The worst case is a graph with no cycle: everything is visited.

4Common mistake

A common mistake is counting every visited neighbour as a cycle in a directed graph:

if (color[v] != 0) return true;  // a black neighbour counts too

With this code the edge 2→3 in the example is taken for a cycle, but there is no way back from 3 to 2. In a directed graph only a grey neighbour is a cycle. In an undirected graph the opposite mistake is made: if the parent is not skipped, every edge on its own looks like a cycle and even a tree with no cycle returns true.

5Try it

During a DFS on a directed graph, what does it tell you if a neighbour of the current vertex is black?

Show the answer

The answer is B. A black vertex is finished and is not on the current path. An edge that reaches it does not close the path.

What does code that forgets the parent check return for the undirected graph with edges 0-1, 1-2, 1-3?

Show the answer

The answer is B. After going from 0 to 1, the list of 1 contains 0, and 0 is grey. If the parent is not skipped, this looks like a cycle even in a tree that has none.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.