Algo-Sim › Graph Traversal
Course Schedule (cycle detection)
Medium · Graph Traversal · step through it in Java, Python and C++ on your own input
Can all courses be finished given prerequisite pairs? Only if the directed graph has no cycle: DFS with three states finds a back edge.
Problem
There are numCourses courses, labelled 0..numCourses − 1. A pair [a, b] means course b must be taken before course a. Return true if it is possible to finish every course.
Constraints
- 1 ≤ numCourses ≤ 2000
- 0 ≤ prerequisites.length ≤ 5000
- All pairs are distinct; a ≠ b
- Possible exactly when the directed graph has no cycle
Edge cases to test
- No prerequisites:
true - A self-prerequisite
[a, a] - A cycle in one component among many
Follow-up questions
- What is the BFS alternative?
- Kahn’s algorithm: repeatedly take nodes with in-degree 0; if some remain, there is a cycle. O(V + E).
- How do you return an order?
- Kahn’s output order, or the reverse of DFS finish order (LC 210).
Solution
Java
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
for (int[] p : prerequisites) adj.get(p[1]).add(p[0]);
// state: 0 = unvisited, 1 = on the current path, 2 = done
int[] state = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (state[i] == 0 && hasCycle(adj, i, state)) return false;
}
return true;
}
private boolean hasCycle(List<List<Integer>> adj, int node, int[] state) {
state[node] = 1;
for (int next : adj.get(node)) {
if (state[next] == 1) return true;
if (state[next] == 0 && hasCycle(adj, next, state)) return true;
}
state[node] = 2;
return false;
}Python
def can_finish(num_courses, prerequisites):
adj = [[] for _ in range(num_courses)]
for course, pre in prerequisites:
adj[pre].append(course)
# state: 0 = unvisited, 1 = on the current path, 2 = done
state = [0] * num_courses
def has_cycle(node):
state[node] = 1
for nxt in adj[node]:
if state[nxt] == 1:
return True
if state[nxt] == 0 and has_cycle(nxt):
return True
state[node] = 2
return False
for i in range(num_courses):
if state[i] == 0 and has_cycle(i):
return False
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> adj = {};
for (int i = 0; i < numCourses; i++)
adj.push_back({});
for (vector<int> &p : prerequisites)
adj[p[1]].push_back(p[0]);
// state: 0 = unvisited, 1 = on the current path, 2 = done
vector<int> state = vector<int>(numCourses);
for (int i = 0; i < numCourses; i++) {
if (state[i] == 0 && hasCycle(adj, i, state))
return false;
}
return true;
}
bool hasCycle(vector<vector<int>> &adj, int node, vector<int> &state) {
state[node] = 1;
for (int next : adj[node]) {
if (state[next] == 1)
return true;
if (state[next] == 0 && hasCycle(adj, next, state))
return true;
}
state[node] = 2;
return false;
}
};
More Graph Traversal problems
- Breadth-First Search (Easy)
- Depth-First Search (Easy)
- Graph Valid Tree (undirected cycle) (Medium)
- Number of Connected Components (DFS) (Medium)
- Is Graph Bipartite? (Medium)
- Clone Graph (Medium)
- Word Ladder (Hard)
- Open the Lock (Medium)