-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
71 lines (62 loc) · 1.95 KB
/
Solution.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
65
66
67
68
69
70
71
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
private:
vector<int> topologicalSort(int const& numCourses,
vector<vector<int>> const& prerequisites) {
vector<vector<int>> adjacencyList(numCourses);
vector<int> inDegree(numCourses, 0);
// Form adjacencyList and update inDegree of courses
// if course A has an directed edge to course B, then course A is a
// prerequisite of B
for (auto const& prerequisite : prerequisites) {
int from = prerequisite[1]; // course B must be taken before course A
int to = prerequisite[0];
adjacencyList[from].push_back(to);
++inDegree[to];
}
queue<int> zeroIn;
for (int i = 0; i < numCourses; ++i) {
if (!inDegree[i]) {
zeroIn.push(i);
}
}
// Pop nodes with zero inDegree, update its neighbours, and add nodes with
// zero inDegree. Repeat until queue is empty
vector<int> result;
result.reserve(numCourses);
while (!zeroIn.empty()) {
int curr = zeroIn.front();
zeroIn.pop();
result.push_back(curr);
for (auto const& neighbour : adjacencyList[curr]) {
--inDegree[neighbour];
if (!inDegree[neighbour]) {
zeroIn.push(neighbour);
}
}
}
if (result.size() < numCourses) {
return {}; // Cycle detected
}
return result;
}
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
// prerequisites[i] = [ai, bi] such that bi must be taken before ai
// Implies some form of topological sort.
// Sort [0..numCourses] such that courses that have to be taken
// first is in front.
vector<int> sortedCourses = topologicalSort(numCourses, prerequisites);
return sortedCourses.size() == numCourses;
}
};