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.
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
DFS With a Parent Check
- Mark every vertex unvisited
- From each unvisited vertex, start a DFS whose entry edge is 'none'
- On entering u, mark it visited
- 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
- 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
Counting Edges Before Searching
- Check E = V − 1; if not, it is not a tree
- Run one DFS or BFS from any vertex
- 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
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.
Related lessons and problems
- Cycle DetectionDirected and undirected methods side by side.
- Directed Graph Cycle DetectionThree states, when edges have direction.
- Disjoint Sets and Union-FindThe structure behind the edge-stream test.
- Kruskal's AlgorithmRejects every edge that would close a cycle.
- Redundant Connection (problem)Find the edge that made the cycle.
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}});
}
}Step through it
Running on edges 0–1, 0–2, 1–3, 3–4, 4–1, 2–5
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
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
Problems to Practise
These start with the plain detection task and move to variants where the edge that closes the cycle is the answer.
- Detect Cycle in an Undirected Graph (DFS): the parent check
- Detect Cycle in an Undirected Graph (BFS): the same idea with a queue
- Redundant Connection: return the edge that closes the cycle, with union-find
- Number of Provinces: count the pieces c used in the V − c edge rule