210. Course Schedule II
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both
courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .// BFS
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { // time: O(V + E); space: O(V + E)
vector<vector<int> > graph(numCourses);
vector<int> indegree(numCourses, 0), res;
for (auto& pre : prerequisites) {
graph[pre[1]].push_back(pre[0]);
++indegree[pre[0]];
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) q.push(i);
}
while (!q.empty()) {
int t = q.front(); q.pop();
res.push_back(t);
for (int a : graph[t]) {
if (--indegree[a] == 0) q.push(a);
}
}
if (res.size() != numCourses) res.clear();
return res;
}Last updated