Leetcode 210 Solution
This article provides solution to leetcode question 210 (course-schedule-ii)
Access this page by simply typing in "lcs 210" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/course-schedule-ii
Solution
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites)
{
vector<int> degrees(numCourses);
multimap<int, int> graph;
for (auto pair : prerequisites)
{
degrees[pair.first]++;
graph.insert(make_pair(pair.second, pair.first));
}
vector<int> res;
queue<int> q;
for (int i = 0; i < degrees.size(); i++)
{
if (degrees[i] == 0)
{
q.push(i);
res.push_back(i);
}
}
while (q.empty() == false)
{
int node = q.front();
q.pop();
for (auto it = graph.find(node); it != graph.end() && it->first == node; ++it)
{
degrees[it->second]--;
if (degrees[it->second] == 0)
{
q.push(it->second);
res.push_back(it->second);
}
}
}
return res.size() == numCourses ? res : vector<int>();
}
};