bfs 3 – topological sorting

1. Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example
Given n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
Return [0,1,2,3] or [0,2,1,3]

拓扑排序

vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
  unordered_map<int, multiset<int>> orders;  // 存依赖关系0-->1
  vector<int> indegrees(numCourses, 0);      // 存
  for (auto i : prerequisites) {
    orders[i.second].insert(i.first);
    indegrees[i.first]++;
  }
  queue<int> q;
  for (int i = 0; i < numCourses; i++) {
    if (indegrees[i] == 0) q.push(i);
  }
  vector<int> res;  // 存入度==0的
  while (!q.empty()) {
    int cur = q.front();
    res.push_back(cur);
    q.pop();
    if (orders.find(cur) == orders.end()) {
      continue;
    }
    for (auto i : orders[cur]) {
      indegrees[i]--;
      if (indegrees[i] == 0) q.push(i);  // push only if 入度==0
    }
  }
  if (res.size() == numCourses) return res;
  return vector<int>();
}