-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
33 lines (31 loc) · 730 Bytes
/
solution.cpp
File metadata and controls
33 lines (31 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <vector>
#include <queue>
using namespace std;
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> valence(numCourses, 0);
// build graph
for (const auto &pre : prerequisites) {
graph[pre[0]].push_back(pre[1]);
valence[pre[1]]++;
}
// get leaf node
queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (!valence[i]) {
q.push(i);
}
}
// remove leaf node, and their parents
while (!q.empty()) {
int curNode = q.front();
q.pop();
numCourses--;
for (int nextNode : graph[curNode]) {
if (--valence[nextNode] == 0) {
q.push(nextNode);
}
}
}
return numCourses == 0;
}