-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207.cpp
47 lines (43 loc) · 1.19 KB
/
207.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
vector<vector<int>> g;
vector<int> indegree;
private:
void buildGraphAndIndegree(int v, vector<pair<int, int>>& edges) {
g = vector<vector<int>>(v, vector<int>());
indegree = vector<int>(v, 0);
for (auto e : edges) {
g[e.second].push_back(e.first);
indegree[e.first]++;
}
return;
}
bool topologicalSort() {
queue<int> q;
int vertices = indegree.size();
int cnt = 0;
for (int i = 0; i < vertices; ++i) {
if (!indegree[i]) {
q.push(i);
cnt++;
}
}
while(!q.empty()) {
int u = q.front(); q.pop();
for (auto v : g[u]) {
indegree[v]--;
if (!indegree[v]) {
q.push(v);
cnt++;
}
}
}
return (cnt == vertices);
}
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
g.clear(); indegree.clear();
buildGraphAndIndegree(numCourses, prerequisites);
return (topologicalSort());
}
};