Skip to content

Commit 7870d84

Browse files
committed
https://leetcode.cn/problems/reachable-nodes-in-subdivided-graph
1 parent d182f23 commit 7870d84

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/reachable-nodes-in-subdivided-graph
49+
4850
https://leetcode.cn/problems/check-if-array-is-sorted-and-rotated
4951

5052
https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum

deno.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
export default function reachableNodes(
2+
edges: number[][],
3+
maxMoves: number,
4+
n: number,
5+
): number {
6+
const adList: [number, number][][] = Array(n)
7+
.fill(0)
8+
.map(() => []);
9+
10+
for (const [u, v, c] of edges) {
11+
adList[u].push([v, c]);
12+
adList[v].push([u, c]);
13+
}
14+
15+
const used = new Map<string, number>();
16+
const visited: boolean[] = Array(n).fill(false);
17+
let reachableNodes = 0;
18+
19+
const pq = new BinaryHeap<[number, number]>((a, b) => a[0] - b[0]);
20+
pq.push([0, 0]);
21+
22+
while (!pq.isEmpty() && (pq.peek() as [number, number])[0] <= maxMoves) {
23+
const [step, u] = pq.pop() as [number, number];
24+
if (visited[u]) {
25+
continue;
26+
}
27+
visited[u] = true;
28+
reachableNodes++;
29+
30+
for (const [v, c] of adList[u]) {
31+
if (c + step + 1 <= maxMoves && !visited[v]) {
32+
pq.push([c + step + 1, v]);
33+
}
34+
used.set(JSON.stringify([u, v]), Math.min(c, maxMoves - step));
35+
}
36+
}
37+
38+
for (const [u, v, c] of edges) {
39+
reachableNodes += Math.min(
40+
c,
41+
(used.get(JSON.stringify([u, v])) ?? 0) +
42+
(used.get(JSON.stringify([v, u])) ?? 0),
43+
);
44+
}
45+
return reachableNodes;
46+
}
47+
import { BinaryHeap } from "https://deno.land/std@0.166.0/collections/binary_heap.ts";

0 commit comments

Comments
 (0)