// Find all nodes with indegree 0 vector<int> start_vec; for (auto it = prev_count.begin(); it != prev_count.end(); it++) { if (it->second == 0) { start_vec.push_back(it->first); } }
// ========DFS========== unordered_set<int> visited; n = start_vec.size(); int p;
for (i = 0; i < n; i++) { stack<int> st;
if (!visited.count(start_vec[i])) { st.push(start_vec[i]); }
while (!st.empty()) { p = st.top(); st.pop();
if (visited.count(p) != 0) { continue; } visited.insert(p);
for (int node : graph[p]) { if (!visited.count(node)) { st.push(node); } } } } return visited.size() == numCourses; } };
Topological Sort
Each time remove a node with indegree 0 (use a queue or stack to store nodes with indegree 0, then decrement the indegree of all neighbors of nodes in the queue or stack by 1; if the indegree becomes 0 after decrement, add it to the queue or stack)
classSolution { public: boolcanFinish(int numCourses, vector<vector<int> > &prerequisites) { // Build graph int i; vector<vector<int> > graph(numCourses); vector<int> indegree(numCourses, 0); // Save the in-degree of each node vector<bool> pushed(numCourses, false); queue<int> que;
for (vector<int> &vec : prerequisites) { graph[vec[1]].push_back(vec[0]); indegree[vec[0]]++; }
// Topological sort // Initialize by adding edges with in-degree 0 first for (i = 0; i < numCourses; i++) { if (indegree[i] == 0) { que.push(i); pushed[i] = true; } }
while (!que.empty()) { i = que.front(); que.pop();
// Each time find an edge with in-degree 0 for (int course : graph[i]) { indegree[course]--;