class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses, 0);
for (auto &e : prerequisites) {
graph[e[1]].push_back(e[0]);
++indegree[e[0]];
}
queue<int> q;
for (int i = 0; i < indegree.size(); ++i) {
if (indegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int curr = q.front();
q.pop();
for (auto &next : graph[curr]) {
--indegree[next];
if (indegree[next] == 0) {
q.push(next);
}
}
--numCourses;
}
return numCourses == 0;
}
};
#define WHITE (0)
#define GRAY (1)
#define BLACK (2)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> graph(numCourses);
for (auto &e : prerequisites) {
graph[e[1]].push_back(e[0]);
}
vector<int> state(numCourses, WHITE);
for (int curr = 0; curr < numCourses; ++curr) {
if (state[curr] == WHITE && hasCycle(graph, state, curr)) {
return false;
}
}
return true;
}
private:
bool hasCycle(vector<vector<int>> &graph, vector<int> &state, int curr) {
state[curr] = GRAY;
for (auto &next : graph[curr]) {
if (state[next] == GRAY) {
// A cycle is detected.
return true;
}
if (state[next] == BLACK) {
// We have visited next and all its descendants.
continue;
}
if (hasCycle(graph, state, next)) {
// A cycle has been detected in the descendants.
return true;
}
}
state[curr] = BLACK;
return false;
}
};
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up