-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-124-topologicalOrder.js
81 lines (67 loc) · 1.55 KB
/
structy-124-topologicalOrder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// https://structy.net/problems/premium/topological-order
// p: graph
// r: arr
const topologicalOrder = (graph) => {
const map = {};
for (const node in graph) {
!(node in map) && (map[node] = 0);
for (const child of graph[node]) {
map[child] = (map[child] || 0) + 1;
}
}
const stack = [];
for (const key in map) {
map[key] === 0 && stack.push(key);
}
const arr = [];
while (stack.length > 0) {
const current = stack.pop();
arr.push(current);
for (const child of graph[current]) {
map[child]--;
map[child] === 0 && stack.push(child);
}
}
return arr;
};
// c a
console.log(
topologicalOrder({
a: ["f"],
b: ["d"],
c: ["a", "f"],
d: ["e"],
e: [],
f: ["b", "e"],
})
);
// a
// f [a]
// b e [a f]
// b [a f e]
// d [a f e b]
// e [a f e b d]
// - [a f e b d e]
// -> ['c', 'a', 'f', 'b', 'd', 'e']
// d [a f e brtw\gbgrszhycdsexfcvg5rtn4 ]
// WRONG
// const topologicalOrder = (graph) => {
// // const
// const arr = [];
// const temp = {};
// for (const key in graph) {
// if (isParent(graph, key)) {
// console.log(key);
// arr.push(key);
// } else {
// temp[key] = graph[key];
// }
// }
// return temp;
// };
// const isParent = (graph, key) => {
// for (const child in graph) {
// if (graph[child].includes(key)) return false;
// }
// return true;
// };