forked from LeadCoding/3-weeks-Google-Prep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1. TopologicalBFS.cpp
32 lines (31 loc) · 1006 Bytes
/
1. TopologicalBFS.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
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> orderedCourses;
unordered_map<int,vector<int>> graph;
vector<int> inDegree(numCourses);
for(auto prerequisite : prerequisites) {
graph[prerequisite[1]].push_back(prerequisite[0]);
inDegree[prerequisite[0]]++;
}
queue<int> topoQueue;
for(int i = 0; i < numCourses; i++) {
if(inDegree[i] == 0) {
topoQueue.push(i);
}
}
while(topoQueue.size()) {
auto course = topoQueue.front();
topoQueue.pop();
orderedCourses.push_back(course);
for(auto nbr : graph[course]) {
inDegree[nbr]--;
if(inDegree[nbr] == 0)topoQueue.push(nbr);
}
}
if(orderedCourses.size() < numCourses) {
return {};
}
return orderedCourses;
}
};