-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourse_schedule.cpp
More file actions
36 lines (29 loc) · 891 Bytes
/
course_schedule.cpp
File metadata and controls
36 lines (29 loc) · 891 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
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses, 0);
for(int i = 0; i < prerequisites.size(); i++){
int pre = prerequisites[i][1];
int course = prerequisites[i][0];
graph[pre].push_back(course);
indegree[course]++;
}
queue<int> q;
for(int i = 0; i < numCourses; i++){
if(indegree[i] == 0)
q.push(i);
}
int visited = 0;
while(!q.empty()){
int curr = q.front();
q.pop();
visited++;
for(int next : graph[curr]){
if(--indegree[next] == 0)
q.push(next);
}
}
return numCourses == visited;
}
};