Can you finish all courses? Only if the prerequisite graph has no cycle. DFS with three colors catches a cycle the instant it revisits a node still on the current path.
White = untouched, Gray = on the current DFS path (in the recursion stack), Black = fully explored and safe.
A directed cycle exists the moment DFS steps onto a gray node, that's a back edge pointing at an ancestor.
black is fine, that subtree is already clearedgray means you looped back onto your own path// color: 0 = white, 1 = gray (on path), 2 = black (done)
bool dfs(int u, vector<vector<int>>& adj, vector<int>& color) {
color[u] = 1; // enter: mark gray
for (int v : adj[u]) {
if (color[v] == 1) return true; // back edge → cycle
if (color[v] == 0 && dfs(v, adj, color)) return true;
}
color[u] = 2; // exit: mark black
return false;
}
bool canFinish(int n, vector<vector<int>>& prereq) {
vector<vector<int>> adj(n);
for (auto& p : prereq) adj[p[1]].push_back(p[0]);
vector<int> color(n, 0);
for (int i = 0; i < n; i++)
if (color[i] == 0 && dfs(i, adj, color))
return false; // cycle → can't finish
return true;
}
Each vertex is colored once; each edge is examined once during DFS.
Adjacency list plus the color array and recursion stack.
A gray-to-gray edge is a back edge, the signature of a directed cycle.
prereq → course so a valid order flows in dependency direction.