Skip to content

Commit 6f00d56

Browse files
committed
topological sort
1 parent 2610d2f commit 6f00d56

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Diff for: algorithm/Graph/topologicalSort/topologicalSort.js

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// lc207 Course Scheduel (https://leetcode.com/problems/course-schedule/)
2+
// BFS: compute indegrees
3+
/**
4+
* @param {number} numCourses
5+
* @param {number[][]} prerequisites
6+
* @return {boolean}
7+
*/
8+
var canFinish = function (numCourses, prerequisites) {
9+
const indegrees = [], preMatrix = [];
10+
for (let [cur, pre] of prerequisites) {
11+
if (!indegrees[cur]) {
12+
indegrees[cur] = 0;
13+
}
14+
indegrees[cur]++;
15+
if (!preMatrix[cur]) {
16+
preMatrix[cur] = [];
17+
}
18+
19+
preMatrix[cur][pre] = 1;
20+
}
21+
22+
const queue = [];
23+
for (let i = 0; i < numCourses; i++) {
24+
if (!indegrees[i]) {
25+
queue.push(i);
26+
}
27+
}
28+
29+
let count = 0;
30+
while (queue.length) {
31+
const cur = queue.shift();
32+
count += 1;
33+
for (let i = 0; i < numCourses; i++) {
34+
if (preMatrix[i] && preMatrix[i][cur]) {
35+
indegrees[i] -= 1;
36+
if (indegrees[i] === 0) {
37+
queue.push(i);
38+
}
39+
}
40+
}
41+
}
42+
43+
return count === numCourses;
44+
};
45+
46+
// DFS
47+
const Node = function (val) {
48+
this.val = val;
49+
this.preRequists = [];
50+
this.done = false;
51+
this.todo = false;
52+
}
53+
54+
const checkCycleExist = (cur, nodeStores) => {
55+
if (cur.done) {
56+
return false;
57+
}
58+
59+
if (cur.todo) {
60+
return true;
61+
}
62+
63+
cur.todo = true;
64+
for (let next of cur.preRequists) {
65+
if (checkCycleExist(nodeStores.get(next), nodeStores)) {
66+
return true;
67+
}
68+
}
69+
70+
cur.todo = false;
71+
cur.done = true;
72+
return false;
73+
};
74+
75+
var canFinish = function (numCourses, prerequisites) {
76+
const nodeStores = new Map();
77+
if (prerequisites.length === 0) {
78+
return true;
79+
}
80+
81+
for (let [cur, pre] of prerequisites) {
82+
if (!nodeStores.has(pre)) {
83+
nodeStores.set(pre, new Node(pre));
84+
}
85+
86+
if (!nodeStores.has(cur)) {
87+
nodeStores.set(cur, new Node(cur));
88+
}
89+
90+
nodeStores.get(cur).preRequists.push(pre);
91+
}
92+
93+
for (let i = 0; i < numCourses; i++) {
94+
if (!nodeStores.has(i)) {
95+
continue;
96+
}
97+
98+
if (checkCycleExist(nodeStores.get(i), nodeStores)) {
99+
return false;
100+
}
101+
}
102+
103+
return true;
104+
};

0 commit comments

Comments
 (0)