-
Notifications
You must be signed in to change notification settings - Fork 1
/
207_Course_Schedule.cpp
47 lines (42 loc) · 1.34 KB
/
207_Course_Schedule.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:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
if(prerequisites.size() == 0) return true;
vector<int> degree(numCourses + 1, 0);
vector<vector<int>> graph(numCourses + 1);
map<int, bool> m;
int total_node = 0;
for(auto node: prerequisites){
int boss = node[1];
int challi = node[0];
degree[challi] += 1;
graph[boss].push_back(challi);
if(m.find(boss) == m.end()){
m[boss] = true;
total_node += 1;
}
}
queue<int> q;
for(int i = 0; i < numCourses; i++)
if(degree[i] == 0){
q.push(i);
}
//cout << graph.size() << endl;
total_node -= q.size();
while(!q.empty()){
int cur = q.front(); q.pop();
for(int i = 0; i < graph[cur].size(); i++){
int child = graph[cur][i];
degree[child] -= 1;
if(degree[child] == 0){
//numCourses -= 1;
total_node -= 1;
q.push(child);
}
}
}
//cout << len << endl;
if(total_node > 0) return false;
return true;
}
};