207. Course Schedule
Last updated
Last updated
time: O(V + E)
space: O(V + E)
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
var canFinish = function (numCourses, prerequisites) {
const incommingEdges = new Array(numCourses).fill(0);
const adjs = {};
for (const [there, here] of prerequisites) {
incommingEdges[there]++;
if (adjs[here] === undefined) {
adjs[here] = [];
}
adjs[here].push(there);
}
const q = [];
for (let i = 0; i < numCourses; i++) {
if (incommingEdges[i] === 0) {
q.push(i);
}
}
const seq = [];
while (q.length > 0) {
const here = q.shift();
seq.push(here);
const adj = adjs[here] ?? [];
for (let i = 0; i < adj.length; i++) {
const there = adj[i];
incommingEdges[there] -= 1;
if (incommingEdges[there] === 0) {
q.push(there);
}
}
}
return seq.length === numCourses ? true : false;
};