1
var minReorder = function (n, connections) {
2
// from: (<from city>, [<to cities>])
3
// to: (<to city>, [<from cities>])
4
const from = new Map(),
5
to = new Map();
6

7
// Function to insert in values in map
8
const insert = (map, key, value) => {
9
if (map.has(key)) {
10
const arr = map.get(key);
11
arr.push(value);
12
map.set(key, arr);
13
} else {
14
map.set(key, [value]);
15
}
16
};
17

18
// Set all values in both maps
19
for (const [a, b] of connections) {
20
insert(from, a, b);
21
insert(to, b, a);
22
}
23

24
// Queue: cities to visit
25
const queue = [0],
26
visited = new Set();
27
let count = 0;
28

29
while (queue.length) {
30
const cur = queue.shift(); // First element in queue
31

32
// Check values in first map
33
if (from.has(cur)) {
34
for (const x of from.get(cur)) {
35
// If visited, do nothing else add to queue
36
if (visited.has(x)) continue;
37
queue.push(x);
38
count++; // Change direction of this path
39
}
40
}
41

42
if (to.has(cur)) {
43
// If visited, do nothing else add to queue
44
for (const x of to.get(cur)) {
45
if (visited.has(x)) continue;
46
queue.push(x);
47
}
48
}
49

50
visited.add(cur); // Mark city as visited
51
}
52

53
return count;
54
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0