-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207. Course Schedule.cc
39 lines (33 loc) · 967 Bytes
/
207. Course Schedule.cc
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
// Using topological sort (kahn's algorithm based on BFS)
// TC: O(V+E)
// SC: O(V+E)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adjList(numCourses, vector<int>());
vector<int> indegree(numCourses, 0);
//O(E)
for (auto &p: prerequisites) {
adjList[p[1]].push_back(p[0]);
indegree[p[0]]++;
}
//O(V)
queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int curr = q.front();
q.pop();
numCourses--;
for (auto vertex: adjList[curr]) {
if(--indegree[vertex] == 0) {
q.push(vertex);
}
}
}
return numCourses == 0;
}
};