Skip to content

Commit 6a72ceb

Browse files
authored
Update 210-course-schedule-ii.js
1 parent 358efc4 commit 6a72ceb

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

210-course-schedule-ii.js

+50
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,53 @@ const findOrder = function(numCourses, prerequisites) {
104104
return true
105105
}
106106
}
107+
108+
// another
109+
110+
/**
111+
* @param {number} numCourses
112+
* @param {number[][]} prerequisites
113+
* @return {number[]}
114+
*/
115+
var findOrder = function(numCourses, prerequisites) {
116+
const inDegree = new Array(numCourses).fill(0);
117+
const graph = {};
118+
for (let i = 0;i < prerequisites.length;i++) {
119+
const e = prerequisites[i];
120+
inDegree[e[0]]++;
121+
if (graph[e[1]]) {
122+
graph[e[1]].push(e[0]);
123+
} else {
124+
graph[e[1]] = [e[0]];
125+
}
126+
}
127+
let q = []
128+
for (let i = 0;i < inDegree.length;i++) {
129+
if (inDegree[i] === 0) {
130+
q.push(i);
131+
}
132+
}
133+
const res = []
134+
let count = 0;
135+
while(q.length) {
136+
const tmp = []
137+
const size = q.length
138+
for(let i = 0;i < size;i++) {
139+
const node = q[i]
140+
res.push(node)
141+
count++
142+
if (graph[node]) {
143+
for (let j = 0;j < graph[node].length;j++) {
144+
inDegree[graph[node][j]]--
145+
if (inDegree[graph[node][j]] === 0) {
146+
tmp.push(graph[node][j])
147+
}
148+
}
149+
}
150+
}
151+
152+
q = tmp
153+
}
154+
155+
return count === numCourses ? res : [];
156+
};

0 commit comments

Comments
 (0)