## 题目

#### 210. 课程表 II

• 例如，想要学习课程 `0` ，你需要先完成课程 `1` ，我们用一个匹配来表示：`[0,1]` 。

``````输入： numCourses = 2, prerequisites = [[1,0]]

``````输入： numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]

``````输入： numCourses = 1, prerequisites = []

• `1 <= numCourses <= 2000`
• `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
• `prerequisites[i].length == 2`
• `0 <= ai, bi < numCourses`
• `ai != bi`
• 所有`[ai, bi]` 互不相同

## 实现

``````/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
let list = new Array(numCourses).fill(0);
let map = new Map();

// 建立拓扑关系
for (let i = 0; i < prerequisites.length; i++) {
const [ a, b ] = prerequisites[i];
list[a]++;
map.set(b, (map.get(b) || []).concat([ a ]));
}

// 记录做完的课程
let doneList = [];
let result = [];
for (let i = 0; i < numCourses; i++) {
if (list[i] === 0) {
doneList.push(i);
result.push(i);
}
}

while (doneList.length) {
// 挨个去广播处通知所有相关的小伙伴
const cur = doneList.shift();
const temp = map.get(cur) || [];

for (let i = 0; i < temp.length; i++) {
list[temp[i]]--;
if (list[temp[i]] === 0) {
doneList.push(temp[i]);
result.push(temp[i]);
}
}
}

return result.length === numCourses ? result : [];
};