-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse-Schedule.cpp
40 lines (40 loc) · 1.1 KB
/
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
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
{
unordered_map<int, int> counts;
for (int i = 0; i < numCourses; ++i)
counts[i] = 0;
for (const vector<int> &pre : prerequisites)
{
int a = pre[0], b = pre[1];
counts[a]++;
};
unordered_map<int, vector<int>> next;
for (const vector<int> &pre : prerequisites)
{
int a = pre[0], b = pre[1];
next[b].push_back(a);
};
while (numCourses > 0)
{
bool flag = false;
for (auto iter = counts.begin(); iter != counts.end(); ++iter)
{
if (iter->second == 0)
{
for (const int &n : next[iter->first])
counts[n]--;
numCourses--;
counts.erase(iter);
flag = true;
break;
};
};
if (!flag)
return false;
};
return true;
}
};