-
Notifications
You must be signed in to change notification settings - Fork 1
/
CourseSchedule_207.cpp
42 lines (34 loc) · 1.17 KB
/
CourseSchedule_207.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
/*
~ Author : leetcode.com/tridib_2003/
~ Problem : 207. Course Schedule
~ Link : https://leetcode.com/problems/course-schedule/
*/
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int> > adj(numCourses, vector<int> ());
vector<int> indegree(numCourses, 0);
vector<int> courseOrder;
for (int i = 0; i < prerequisites.size(); ++i) {
int src = prerequisites[i][1];
int dest = prerequisites[i][0];
adj[src].emplace_back(dest);
++indegree[dest];
}
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (indegree[i] == 0)
q.push(i);
while (!q.empty()) {
int currVertex = q.front();
q.pop();
courseOrder.emplace_back(currVertex);
for (auto itr = adj[currVertex].begin(); itr != adj[currVertex].end(); ++itr)
if (--indegree[*itr] == 0)
q.push(*itr);
}
if (courseOrder.size() == numCourses)
return true;
return false;
}
};