-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcourse-schedule.cpp
64 lines (62 loc) · 1.79 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Time: O(|V| + |E|)
// Space: O(|E|)
// Kahn’s algorithm (bfs solution)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
unordered_map<int, vector<int>> adj;
unordered_map<int, int> in_degree;
for (const auto& p : prerequisites) {
++in_degree[p[0]];
adj[p[1]].emplace_back(p[0]);
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (!in_degree.count(i)) {
q.emplace(i);
}
}
vector<int> result;
while (!q.empty()) {
const auto node = q.front(); q.pop();
result.emplace_back(node);
for (const auto& i : adj[node]) {
if (!--in_degree[i]) {
q.emplace(i);
}
}
}
return size(result) == numCourses;
}
};
// Time: O(|V| + |E|)
// Space: O(|E|)
// dfs solution
class Solution2 {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
unordered_map<int, vector<int>> adj;
unordered_map<int, int> in_degree;
for (const auto& p : prerequisites) {
++in_degree[p[0]];
adj[p[1]].emplace_back(p[0]);
}
vector<int> stk;
for (int i = 0; i < numCourses; ++i) {
if (!in_degree.count(i)) {
stk.emplace_back(i);
}
}
vector<int> result;
while (!stk.empty()) {
const auto node = stk.back(); stk.pop_back();
result.emplace_back(node);
for (const auto& i : adj[node]) {
if (!--in_degree[i]) {
stk.emplace_back(i);
}
}
}
return size(result) == numCourses;
}
};