Lesson 11 · Problem-solving methods

Undirected Graph Cycle Detection

In an undirected graph every edge can be walked both ways, so the search must ignore the edge it arrived on. After that, any visited neighbour proves a cycle. Counting edges against vertices and merging sets give the same answer from other angles.

Undirected Graph Cycle Detection concept diagramThree undirected graphs. A tree with 6 vertices and 5 edges has no cycle. Adding a sixth edge between vertices e and c closes the cycle e, b, a, c. Two vertices joined by two parallel edges form a cycle of length two, found only when the search skips its entry edge by id rather than by vertex.Tree: V − 1 edges6 vertices, 5 edges, no cycleabcdefOne more edge: a cycle6 vertices, 6 edgesabcdefe – c joins two vertices thatwere already connectedMultigraph: 2 edges2 vertices, 2 parallel edgesuvedge #1edge #2skip parent vertex: missedskip entry edge id: founda forest with V vertices and c pieces has V − c edges; every edge beyond that closes a cycle
1

Why Walking Back Is Not a Cycle

An undirected edge between a and b is stored twice: b appears in a's list and a in b's. So a search that steps from a to b immediately sees a among b's neighbours, already visited. If 'visited neighbour' meant 'cycle', every graph with a single edge would have one.

A real undirected cycle needs a route back that uses different edges. In a simple graph that means at least three vertices, such as a triangle. The directed method from directed graph cycle detection does not transfer: it would treat the way back along the same edge as a back edge. The cycle detection overview compares the two cases side by side.

  • Same edge walked back and forth: not a cycle
  • A different edge leading to an already visited vertex: a cycle
  • Exceptions in a multigraph: two parallel edges, or an edge from a vertex to itself
2

DFS With a Parent Check

  1. Mark every vertex unvisited
  2. From each unvisited vertex, start a DFS whose entry edge is 'none'
  3. On entering u, mark it visited
  4. For each edge u – v other than the entry edge: if v is unvisited, record u as its parent and recurse; if v is visited, a cycle exists
  5. If no search reports one, the graph is a forest

The fix is the parent check in DFS: remember which edge brought the search into each vertex and ignore that one edge when looking at the neighbours. Every other neighbour that is already visited proves a cycle.

Why does that work? In an undirected depth-first search, an edge that is not a tree edge always joins a vertex to one of its ancestors; there are no cross edges, because the search would have walked such an edge as a tree edge first. So the visited neighbour v is above u in the DFS tree. The tree edges lead from v down to u, and the edge u – v leads back up. Two colours are enough, unlike the three needed for directed graphs.

  • Time O(V + E), space O(V)
  • The first non-tree edge found ends the search; a forest is the only graph that makes it all the way through
  • BFS works the same way: store each vertex's parent and ignore that one edge
3

Counting Edges Before Searching

  1. Check E = V − 1; if not, it is not a tree
  2. Run one DFS or BFS from any vertex
  3. If it reaches all V vertices, the graph is a tree: connected, and with that edge count it cannot hide a cycle

A tree on V vertices has exactly V − 1 edges. A forest made of c separate trees has V − c. Each extra edge joins two vertices that were already connected, which closes a cycle. So E ≥ V is enough to answer 'yes' without looking at the graph at all.

The count cannot prove the opposite. Six vertices and five edges can be a tree, or a triangle next to a separate path of three vertices. That is why the test for whether a graph is a tree has two parts.

  • To check if a graph is a tree, either the parent-check DFS or 'E = V − 1 and connected' works
  • Connected with E = V − 1 already rules out a cycle; no parent check needed
Key reference

Terms, operations, and practical uses

Key terms

  • Entry edgeThe edge that brought the search into a vertex; the only one it must ignore.
  • ForestAn undirected graph with no cycle: one or more trees.
  • V − c ruleA forest with V vertices and c pieces has exactly V − c edges.
  • MultigraphA graph that allows parallel edges and self-loops, both of which are cycles.
Implementation

Code in Python, C++ and Java

import sys

sys.setrecursionlimit(10000)


def find_cycle(n, edges):
    graph = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        graph[u].append((v, i))
        graph[v].append((u, i))
    seen = [False] * n
    parent = [-1] * n

    def dfs(u, entry):
        seen[u] = True
        for v, i in graph[u]:
            if i == entry:
                continue
            if seen[v]:
                cycle, x = [u], u
                while x != v:
                    x = parent[x]
                    cycle.append(x)
                cycle.reverse()
                return cycle + [cycle[0]]
            parent[v] = u
            found = dfs(v, i)
            if found:
                return found
        return None

    for start in range(n):
        if not seen[start]:
            found = dfs(start, -1)
            if found:
                return found
    return None


def first_closing_edge(n, edges):
    root = list(range(n))

    def find(x):
        while root[x] != x:
            root[x] = root[root[x]]
            x = root[x]
        return x

    for u, v in edges:
        a, b = find(u), find(v)
        if a == b:
            return (u, v)
        root[a] = b
    return None


def show(name, n, edges):
    cycle = find_cycle(n, edges)
    print(name + ":", " - ".join(map(str, cycle)) if cycle else "no cycle", end="")
    edge = first_closing_edge(n, edges)
    print(" | union-find:", f"edge {edge[0]}-{edge[1]}" if edge else "no cycle")


graph = [(0, 1), (0, 2), (1, 3), (3, 4), (4, 1), (2, 5)]
show("graph", 6, graph)
show("tree", 6, graph[:4] + graph[5:])
show("path", 3, [(0, 1), (1, 2)])
show("parallel", 2, [(0, 1), (0, 1)])
show("self-loop", 2, [(0, 1), (1, 1)])
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

struct Finder {
    vector<vector<pair<int, int>>> graph;
    vector<bool> seen;
    vector<int> parent, cycle;

    Finder(int n, const vector<pair<int, int>>& edges) : graph(n), seen(n, false), parent(n, -1) {
        for (int i = 0; i < (int)edges.size(); i++) {
            graph[edges[i].first].push_back({edges[i].second, i});
            graph[edges[i].second].push_back({edges[i].first, i});
        }
    }

    bool dfs(int u, int entry) {
        seen[u] = true;
        for (auto [v, i] : graph[u]) {
            if (i == entry) continue;
            if (seen[v]) {
                cycle.push_back(u);
                for (int x = u; x != v;) { x = parent[x]; cycle.push_back(x); }
                reverse(cycle.begin(), cycle.end());
                cycle.push_back(cycle[0]);
                return true;
            }
            parent[v] = u;
            if (dfs(v, i)) return true;
        }
        return false;
    }

    bool run() {
        for (int s = 0; s < (int)graph.size(); s++)
            if (!seen[s] && dfs(s, -1)) return true;
        return false;
    }
};

int findRoot(vector<int>& root, int x) {
    while (root[x] != x) { root[x] = root[root[x]]; x = root[x]; }
    return x;
}

void show(const string& name, int n, const vector<pair<int, int>>& edges) {
    Finder f(n, edges);
    cout << name << ": ";
    if (f.run()) {
        for (size_t i = 0; i < f.cycle.size(); i++) cout << (i ? " - " : "") << f.cycle[i];
    } else cout << "no cycle";
    vector<int> root(n);
    for (int i = 0; i < n; i++) root[i] = i;
    cout << " | union-find: ";
    for (auto [u, v] : edges) {
        int a = findRoot(root, u), b = findRoot(root, v);
        if (a == b) { cout << "edge " << u << "-" << v << "\n"; return; }
        root[a] = b;
    }
    cout << "no cycle\n";
}

int main() {
    vector<pair<int, int>> graph = {{0, 1}, {0, 2}, {1, 3}, {3, 4}, {4, 1}, {2, 5}};
    show("graph", 6, graph);
    show("tree", 6, {{0, 1}, {0, 2}, {1, 3}, {3, 4}, {2, 5}});
    show("path", 3, {{0, 1}, {1, 2}});
    show("parallel", 2, {{0, 1}, {0, 1}});
    show("self-loop", 2, {{0, 1}, {1, 1}});
}
import java.util.*;

public class Main {
    static List<List<int[]>> graph;
    static boolean[] seen;
    static int[] parent;
    static List<Integer> cycle;

    static boolean dfs(int u, int entry) {
        seen[u] = true;
        for (int[] e : graph.get(u)) {
            int v = e[0], i = e[1];
            if (i == entry) continue;
            if (seen[v]) {
                cycle.add(u);
                for (int x = u; x != v;) { x = parent[x]; cycle.add(x); }
                Collections.reverse(cycle);
                cycle.add(cycle.get(0));
                return true;
            }
            parent[v] = u;
            if (dfs(v, i)) return true;
        }
        return false;
    }

    static List<Integer> findCycle(int n, int[][] edges) {
        graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        for (int i = 0; i < edges.length; i++) {
            graph.get(edges[i][0]).add(new int[]{edges[i][1], i});
            graph.get(edges[i][1]).add(new int[]{edges[i][0], i});
        }
        seen = new boolean[n];
        parent = new int[n];
        cycle = new ArrayList<>();
        for (int s = 0; s < n; s++)
            if (!seen[s] && dfs(s, -1)) return cycle;
        return null;
    }

    static int find(int[] root, int x) {
        while (root[x] != x) { root[x] = root[root[x]]; x = root[x]; }
        return x;
    }

    static String firstClosingEdge(int n, int[][] edges) {
        int[] root = new int[n];
        for (int i = 0; i < n; i++) root[i] = i;
        for (int[] e : edges) {
            int a = find(root, e[0]), b = find(root, e[1]);
            if (a == b) return "edge " + e[0] + "-" + e[1];
            root[a] = b;
        }
        return "no cycle";
    }

    static void show(String name, int n, int[][] edges) {
        List<Integer> c = findCycle(n, edges);
        StringBuilder sb = new StringBuilder(name + ": ");
        if (c == null) sb.append("no cycle");
        else for (int i = 0; i < c.size(); i++) sb.append(i > 0 ? " - " : "").append(c.get(i));
        System.out.println(sb + " | union-find: " + firstClosingEdge(n, edges));
    }

    public static void main(String[] args) {
        show("graph", 6, new int[][]{{0, 1}, {0, 2}, {1, 3}, {3, 4}, {4, 1}, {2, 5}});
        show("tree", 6, new int[][]{{0, 1}, {0, 2}, {1, 3}, {3, 4}, {2, 5}});
        show("path", 3, new int[][]{{0, 1}, {1, 2}});
        show("parallel", 2, new int[][]{{0, 1}, {0, 1}});
        show("self-loop", 2, new int[][]{{0, 1}, {1, 1}});
    }
}
Watch it run

Step through it

Running on edges 0–1, 0–2, 1–3, 3–4, 4–1, 2–5

skip the entry edge; any other visited neighbour = cycle012345PARENT0: –1: –2: –3: –4: –5: –edges 0–1, 0–2, 1–3, 3–4, 4–1, 2–5Each edge appears twice in the neighbour lists.
Step 1

Six vertices, six edges

Each edge can be walked both ways, so it sits in two neighbour lists: 1 is in 0's list and 0 is in 1's. The search will remember, for each vertex, the vertex it came from (its parent), so it can ignore that one way back.

Output
1 / 12
4

Union-Find on a Stream of Edges

Sometimes there is no graph to search, only edges arriving one at a time: cables being laid, roads being added, Kruskal's algorithm picking cheap edges. A disjoint set keeps the connected pieces as sets. For each new edge, find the set of both ends. Different sets: merge them. Same set: the ends were already connected, so this edge closes a cycle.

With union by rank and path compression each edge costs almost constant time, O(E α(V)) in all. It also names the exact edge that created the first cycle, which is the question in Redundant Connection. It does not list the cycle's vertices; for that, use the DFS.

  • Works when edges arrive online and never need to be stored as a graph
  • Kruskal's minimum spanning tree rejects exactly the edges this test flags
  • Undirected graphs only: in a directed graph two vertices in one set may still have no directed loop
5

Parallel Edges, Self-Loops and Printing the Cycle

In a multigraph two edges can join the same pair of vertices, and together they form a cycle of length two. If the search skips 'the parent vertex' rather than 'the entry edge', it skips both of them and misses it. Give each edge an id when building the lists and skip only the id it arrived by.

An edge from a vertex to itself is a cycle of length one. With edge ids it needs no special case: the search meets its own, already visited vertex along an edge that is not the entry edge.

To print the cycle, keep the parent of each vertex. When u finds the visited vertex v, step from u through parents until you reach v, then add u again: in the tracer this gives 1 – 3 – 4 – 1.

  • Skip by edge id, not by neighbour
  • Self-loops and parallel edges need no extra code once ids are used
  • Start a search from every unvisited vertex so cycles in other pieces are found
6

Problems to Practise

These start with the plain detection task and move to variants where the edge that closes the cycle is the answer.