forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207.course-schedule.cpp
More file actions
39 lines (34 loc) · 1.05 KB
/
207.course-schedule.cpp
File metadata and controls
39 lines (34 loc) · 1.05 KB
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
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
unordered_map<int, vector<int>> graph;
unordered_map<int, int> indegree;
for (auto courses : prerequisites) {
indegree[courses.first] += 1;
graph[courses.second].push_back(courses.first);
}
queue<int> starts;
for (auto i = 0; i < numCourses; ++i)
{
if (indegree.count(i) == 0)
{
starts.push(i);
}
}
while (!starts.empty()) {
int course = starts.front();
starts.pop();
vector<int> nodes = graph[course];
for (auto i = 0; i < nodes.size(); ++i)
{
indegree[nodes[i]] -= 1;
if (indegree[nodes[i]] == 0)
{
starts.push(nodes[i]);
indegree.erase(nodes[i]);
}
}
}
return indegree.empty();
}
};