-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-125-safeCracking.js
64 lines (51 loc) · 1.18 KB
/
structy-125-safeCracking.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
// https://structy.net/problems/premium/safe-cracking
// p: arr
// r: str
const safeCracking = (hints) => {
const graph = buildGraph(hints);
const map = {};
// get map
for (const node in graph) {
!(node in map) && (map[node] = 0);
for (const nei of graph[node]) {
map[nei] = (map[nei] || 0) + 1;
}
}
// find first num of combination
const stack = [];
for (const key in map) {
map[key] === 0 && stack.push(key.toString());
}
// get combination:
let combi = "";
while (stack.length > 0) {
const current = stack.pop();
combi += current;
for (const next of graph[current]) {
map[next]--;
map[next] === 0 && stack.push(next.toString());
}
}
return graph;
};
const buildGraph = (edges) => {
const graph = {};
for (const edge of edges) {
const [a, b] = edge;
graph[a] === undefined && (graph[a] = []);
graph[b] === undefined && (graph[b] = []);
graph[a].push(b);
}
return combi;
};
console.log(
safeCracking([
[3, 1], //
[4, 7], //
[5, 9], //
[4, 3], //
[7, 3], //
[3, 5], //
[9, 1], //
])
); // -> '473591'