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.
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
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;
} from collections import deque
def adjacency(n, edges, directed):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
if not directed:
adj[v].append(u)
return adj
def has_cycle_undirected(n, edges): # a seen neighbour that is not the parent
adj, seen = adjacency(n, edges, False), [False] * n
def dfs(u, parent):
seen[u] = True
for v in adj[u]:
if v == parent:
continue # the edge we came in on
if seen[v] or dfs(v, u):
return True
return False
return any(not seen[i] and dfs(i, -1) for i in range(n))
def has_cycle_directed(n, edges): # 0 = new, 1 = on the current path, 2 = finished
adj, state = adjacency(n, edges, True), [0] * n
def dfs(u):
state[u] = 1
for v in adj[u]:
if state[v] == 1 or (state[v] == 0 and dfs(v)):
return True # back edge to the current path
state[u] = 2
return False
return any(state[i] == 0 and dfs(i) for i in range(n))
def is_bipartite(graph): # 0 = none, 1 and -1 = the two sides
color = [0] * len(graph)
for s in range(len(graph)):
if color[s]:
continue
color[s], q = 1, deque([s])
while q:
u = q.popleft()
for v in graph[u]:
if color[v] == color[u]:
return False # an edge inside one side: odd cycle
if color[v] == 0:
color[v] = -color[u]
q.append(v)
return True vector<vector<int>> adjacency(int n, vector<vector<int>>& edges, bool directed) {
vector<vector<int>> adj(n);
for (auto& e : edges) { adj[e[0]].push_back(e[1]); if (!directed) adj[e[1]].push_back(e[0]); }
return adj;
}
// undirected: a seen neighbour that is not the parent closes a cycle
bool dfsUndirected(int u, int parent, vector<vector<int>>& adj, vector<bool>& seen) {
seen[u] = true;
for (int v : adj[u]) {
if (v == parent) continue; // the edge we came in on
if (seen[v] || dfsUndirected(v, u, adj, seen)) return true;
}
return false;
}
bool hasCycleUndirected(int n, vector<vector<int>>& edges) {
auto adj = adjacency(n, edges, false);
vector<bool> seen(n, false);
for (int i = 0; i < n; i++) // every component
if (!seen[i] && dfsUndirected(i, -1, adj, seen)) return true;
return false;
}
// directed: state 0 = new, 1 = on the current path, 2 = finished
bool dfsDirected(int u, vector<vector<int>>& adj, vector<int>& state) {
state[u] = 1;
for (int v : adj[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;
}
bool hasCycleDirected(int n, vector<vector<int>>& edges) {
auto adj = adjacency(n, edges, true);
vector<int> state(n, 0);
for (int i = 0; i < n; i++) if (state[i] == 0 && dfsDirected(i, adj, state)) return true;
return false;
}
// two-colouring with BFS: an edge inside one colour means an odd cycle
bool isBipartite(vector<vector<int>>& graph) {
vector<int> color(graph.size(), 0); // 0 = none, 1 and -1 = the two sides
for (int s = 0; s < (int)graph.size(); s++) {
if (color[s] != 0) continue;
queue<int> q; q.push(s);
color[s] = 1;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : graph[u]) {
if (color[v] == color[u]) return false;
if (color[v] == 0) { color[v] = -color[u]; q.push(v); }
}
}
}
return true;
} function adjacency(n, edges, directed) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); if (!directed) adj[v].push(u); }
return adj;
}
// undirected: a seen neighbour that is not the parent closes a cycle
function hasCycleUndirected(n, edges) {
const adj = adjacency(n, edges, false), seen = new Array(n).fill(false);
const dfs = (u, parent) => {
seen[u] = true;
for (const v of adj[u]) {
if (v === parent) continue; // the edge we came in on
if (seen[v] || dfs(v, u)) return true;
}
return false;
};
for (let i = 0; i < n; i++) if (!seen[i] && dfs(i, -1)) return true;
return false;
}
// directed: state 0 = new, 1 = on the current path, 2 = finished
function hasCycleDirected(n, edges) {
const adj = adjacency(n, edges, true), state = new Array(n).fill(0);
const dfs = (u) => {
state[u] = 1;
for (const v of adj[u]) {
if (state[v] === 1) return true; // back edge: v is still on the path
if (state[v] === 0 && dfs(v)) return true;
}
state[u] = 2;
return false;
};
for (let i = 0; i < n; i++) if (state[i] === 0 && dfs(i)) return true;
return false;
}
// two-colouring with BFS: an edge inside one colour means an odd cycle
function isBipartite(graph) {
const color = new Array(graph.length).fill(0); // 0 = none, 1 and -1 = the two sides
for (let s = 0; s < graph.length; s++) {
if (color[s] !== 0) continue;
const q = [s];
color[s] = 1;
for (let head = 0; head < q.length; head++) {
const u = q[head];
for (const v of graph[u]) {
if (color[v] === color[u]) return false;
if (color[v] === 0) { color[v] = -color[u]; q.push(v); }
}
}
}
return true;
} The variations
-
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.
Now you solve -
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.
-
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 -
4More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
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.