1
var reachableNodes = function (edges, maxMoves, n) {
2
const g = Array.from({ length: n }, () => []);
3

4
for (let [u, v, cnt] of edges) {
5
g[u].push([v, cnt + 1]);
6
g[v].push([u, cnt + 1]);
7
}
8

9
// find min budget to reach from 0 to all nodes
10
const budget = new Array(n).fill(Infinity);
11
budget[0] = 0;
12
const dijkstra = () => {
13
// heap will be collection [node, weight]
14
const heap = new MinPriorityQueue({ priority: (x) => x[1] });
15
heap.enqueue([0, 0]);
16
while (heap.size()) {
17
const [n, c] = heap.dequeue().element;
18
for (let [nextNode, cost] of g[n]) {
19
let temp = c + cost;
20
if (budget[nextNode] > temp) {
21
budget[nextNode] = temp;
22
heap.enqueue([nextNode, temp]);
23
}
24
}
25
}
26
};
27
dijkstra();
28

29
// add to sum all reachable nodes from 0 with max move
30
let vis = 0;
31
for (let w of budget) vis += w <= maxMoves;
32

33
// add intermediate nodes between edges with available budget
34
for (let [a, b, c] of edges) {
35
let [availableFromA, availableFromB] = [
36
maxMoves - budget[a],
37
maxMoves - budget[b],
38
];
39
if (availableFromA < 0 || availableFromB < 0) {
40
vis += Math.max(availableFromA, 0) + Math.max(availableFromB, 0);
41
} else {
42
const total = availableFromA + availableFromB;
43
vis += total - Math.max(total - c, 0);
44
}
45
}
46

47
return vis;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0