Graphs · Pattern 7 of 14

Cycle detection and bipartite graphs

Undirected graph: a cycle is a visited neighbour that is not the node you came from. Directed graph: a cycle is an edge back to a node still on the current DFS path. Two-colouring finds odd cycles.

4 variations · 6 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Does the graph contain a loop?
  • Can these tasks all finish, or is there a circular dependency?
  • Split the nodes into two groups with every edge going across

The template

Cycle Detection
List<List<Integer>> adjacency(int n, int[][] edges, boolean directed) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) { adj.get(e[0]).add(e[1]); if (!directed) adj.get(e[1]).add(e[0]); }
    return adj;
}

// undirected: a seen neighbour that is not the parent closes a cycle
boolean hasCycleUndirected(int n, int[][] edges) {
    List<List<Integer>> adj = adjacency(n, edges, false);
    boolean[] seen = new boolean[n];
    for (int i = 0; i < n; i++)                          // every component
        if (!seen[i] && dfsUndirected(i, -1, adj, seen)) return true;
    return false;
}
boolean dfsUndirected(int u, int parent, List<List<Integer>> adj, boolean[] seen) {
    seen[u] = true;
    for (int v : adj.get(u)) {
        if (v == parent) continue;                       // the edge we came in on
        if (seen[v] || dfsUndirected(v, u, adj, seen)) return true;
    }
    return false;
}

// directed: state 0 = new, 1 = on the current path, 2 = finished
boolean hasCycleDirected(int n, int[][] edges) {
    List<List<Integer>> adj = adjacency(n, edges, true);
    int[] state = new int[n];
    for (int i = 0; i < n; i++) if (state[i] == 0 && dfsDirected(i, adj, state)) return true;
    return false;
}
boolean dfsDirected(int u, List<List<Integer>> adj, int[] state) {
    state[u] = 1;
    for (int v : adj.get(u)) {
        if (state[v] == 1) return true;                  // back edge: v is still on the path
        if (state[v] == 0 && dfsDirected(v, adj, state)) return true;
    }
    state[u] = 2;
    return false;
}

// two-colouring with BFS: an edge inside one colour means an odd cycle
boolean isBipartite(int[][] graph) {
    int[] color = new int[graph.length];                 // 0 = none, 1 and -1 = the two sides
    for (int s = 0; s < graph.length; s++) {
        if (color[s] != 0) continue;
        Deque<Integer> q = new ArrayDeque<>(List.of(s));
        color[s] = 1;
        while (!q.isEmpty()) {
            int u = q.poll();
            for (int v : graph[u]) {
                if (color[v] == color[u]) return false;
                if (color[v] == 0) { color[v] = -color[u]; q.offer(v); }
            }
        }
    }
    return true;
}

The variations

  1. 1Undirected: a visited neighbour that is not your parent

    Do a DFS and remember where you came from. Seeing an already visited node by any other edge means there are two ways to reach it: a cycle. On a grid, the parent is the previous cell and cells of the same letter are the edges.

  2. 2Directed: an edge back onto the current path

    Colour nodes new, on the path or finished. Reaching a node that is still on the path is a back edge, and only that is a cycle. Reaching a finished node is fine: it was explored from another branch.

  3. 3Two-colouring (bipartite)

    Give the start colour 1 and every neighbour the other colour. If an edge ever joins two nodes of the same colour, the graph has an odd cycle and cannot be split. "People who dislike each other" is the same check.

    Now you solve
  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Using the undirected "seen and not the parent" test on a directed graph: a diamond A→B, A→C, B→D, C→D has no cycle but looks like one.
  • Using one visited array for directed graphs: a node finished in an earlier search is not a cycle. You need the third state, "on the current path".
  • Colouring only from node 0: the graph may be disconnected, so start a new colouring from every uncoloured node.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.