-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse Schedule.cpp
More file actions
38 lines (35 loc) · 1020 Bytes
/
Course Schedule.cpp
File metadata and controls
38 lines (35 loc) · 1020 Bytes
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
// Bread-first-search
// Space complexity: O(n)
// Time complexity: O(n)
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
/** build the graph */
vector<int> inCourses(numCourses, 0);
unordered_map<int, vector<int>> mp;
int nodeVisited = 0;
for(auto p : prerequisites) {
inCourses[p.first]++;
mp[p.second].push_back(p.first);
}
/** bread-first search */
queue<int> q;
for(int i=0; i<inCourses.size(); ++i) {
if(inCourses[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int temp = q.front();
q.pop();
nodeVisited++;
for (auto c : mp[temp]) {
if (--inCourses[c] == 0) {
q.push(c);
}
}
}
/** check if the graph has cycle */
return nodeVisited == numCourses;
}
};