Detect a cycle in a directed graph
Pattern: Cycle detection
DFS with three states: unvisited, on the current path, finished. An edge to a vertex still on the current path means you can return to it: a cycle. An edge to a finished vertex is harmless.
The problem
Return whether a directed graph contains a cycle. Vertices are numbered from 0 and each edge is given as [u, v]. (an edge goes from u to v). A self-loop counts.
Think first
- Why is 'already visited' not enough?
- Which visited vertices matter?
- What other method also works?
Hints
Brute force, and why it fails
From every vertex, search for a path back to itself: O(V × (V + E)).
The key insight
The current DFS path is exactly the set of vertices you can still get back to, so an edge into it is a cycle.
Dry run
| path | 0 1 2 |
|---|
n = 3, edges 0 → 1, 1 → 2, 2 → 0. DFS from 0: 0 and 1 are on the path, then 2.
Step 1 of 3
The plan
dfs(u): state[u] = 1
for v: if state[v] == 1: cycle; if state[v] == 0: dfs(v)
state[u] = 2
Complexity
- Time
O(V + E)- Space
O(V)
Each vertex and edge once.
Edge cases
- A self-loop: true.
- A DAG with shared descendants: false.
- Several pieces.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean isCyclic(int n, int[][] edges) {
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]);
int[] state = new int[n]; // 0 unvisited, 1 on the current path, 2 finished
for (int i = 0; i < n; i++) if (state[i] == 0 && dfs(i, adj, state)) return true;
return false;
}
private boolean dfs(int u, List<List<Integer>> adj, int[] state) {
state[u] = 1;
for (int v : adj.get(u)) {
if (state[v] == 1) return true; // an edge back to the current path: a cycle
if (state[v] == 0 && dfs(v, adj, state)) return true;
}
state[u] = 2;
return false;
}
}C++
class Solution {
public:
bool isCyclic(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (const vector<int>& e : edges) adj[e[0]].push_back(e[1]);
vector<int> state(n, 0); // 0 unvisited, 1 on the current path, 2 finished
for (int i = 0; i < n; i++) if (state[i] == 0 && dfs(i, adj, state)) return true;
return false;
}
bool dfs(int u, vector<vector<int>>& adj, vector<int>& state) {
state[u] = 1;
for (int v : adj[u]) {
if (state[v] == 1) return true; // an edge back to the current path: a cycle
if (state[v] == 0 && dfs(v, adj, state)) return true;
}
state[u] = 2;
return false;
}
};Python
class Solution:
def isCyclic(self, n: int, edges: list[list[int]]) -> bool:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
state = [0] * n # 0 unvisited, 1 on the current path, 2 finished
def dfs(u) -> bool:
state[u] = 1
for v in adj[u]:
if state[v] == 1 or (state[v] == 0 and dfs(v)):
return True # an edge back to the current path: a cycle
state[u] = 2
return False
return any(state[i] == 0 and dfs(i) for i in range(n))Common mistakes
- Using a single visited flag.
- Forgetting to start DFS from every unvisited vertex.