|
1 |
| -// https://leetcode.com/problems/network-delay-time/solution/ |
2 |
| -function networkDelayTime(times: number[][], N: number, K: number): number { |
3 |
| - const graph = new Map<number, [number, number][]>(Array(N).fill(0).map((_, i) => [i + 1, []])); |
4 |
| - times.forEach(([u, v, w]) => graph.get(u)?.push([v, w])); |
| 1 | +const { PriorityQueue, Queue } = require('../../src/index'); |
5 | 2 |
|
6 |
| - const queue = new Queue([[K, 0]]); |
7 |
| - const seen = Array(N + 1).fill(Infinity); |
| 3 | +// tag::description[] |
| 4 | +function networkDelayTime(times, N, K) { |
| 5 | + // end::description[] |
| 6 | + // tag::placeholder[] |
| 7 | + // write your code here... |
| 8 | + // end::placeholder[] |
| 9 | + // tag::solution[] |
| 10 | + const graph = new Map(Array(N).fill(0).map((_, i) => [i + 1, []])); |
| 11 | + times.forEach(([u, v, w]) => graph.get(u).push([v, w])); |
8 | 12 |
|
9 |
| - while (queue.size()) { |
10 |
| - const [node, dist] = queue.dequeue(); |
11 |
| - seen[node] = Math.min(seen[node], dist); |
| 13 | + const q = new PriorityQueue([[0, K]]); |
| 14 | + const dist = new Map(); |
12 | 15 |
|
13 |
| - for (const [adj, w] of graph.get(node) || []) { |
14 |
| - if (seen[adj] > dist + w) queue.enqueue([adj, dist + w]); |
| 16 | + while (q.size) { |
| 17 | + const [d, n] = q.dequeue(); |
| 18 | + |
| 19 | + if (dist.has(n)) continue; |
| 20 | + dist.set(n, d); |
| 21 | + |
| 22 | + for (const [adj, w] of graph.get(n)) { |
| 23 | + if (!dist.has(adj)) q.enqueue([d + w, adj]); |
15 | 24 | }
|
16 | 25 | }
|
17 | 26 |
|
18 |
| - const max = Math.max(...seen.slice(1)); |
19 |
| - return max === Infinity ? -1 : max; |
20 |
| -}; |
| 27 | + return dist.size === N ? Math.max(...dist.values()) : -1; |
| 28 | + // end::solution[] |
| 29 | + // tag::description[] |
| 30 | +} |
| 31 | +// end::description[] |
| 32 | + |
| 33 | +// tag::networkDelayTimeQueue[] |
| 34 | +function networkDelayTimeQueue(times, N, K) { |
| 35 | + const graph = new Map(Array(N).fill(0).map((_, i) => [i + 1, []])); |
| 36 | + times.forEach(([u, v, w]) => graph.get(u).push([v, w])); |
| 37 | + |
| 38 | + const q = new Queue([[0, K]]); |
| 39 | + const dist = new Map(); |
21 | 40 |
|
22 |
| -/* |
23 |
| -[[2,1,1],[2,3,1],[3,4,1]] |
24 |
| -4 |
25 |
| -2 |
| 41 | + while (q.size) { |
| 42 | + const [d, n] = q.dequeue(); |
| 43 | + |
| 44 | + dist.set(n, dist.has(n) ? Math.min(dist.get(n), d) : d); |
| 45 | + |
| 46 | + for (const [adj, w] of graph.get(n)) { |
| 47 | + if (!dist.has(adj) || dist.get(adj) > d + w) { |
| 48 | + q.enqueue([d + w, adj]); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
26 | 52 |
|
| 53 | + return dist.size === N ? Math.max(...dist.values()) : -1; |
| 54 | +} |
| 55 | +// end::networkDelayTimeQueue[] |
27 | 56 |
|
28 |
| -*/ |
| 57 | +module.exports = { networkDelayTime, networkDelayTimeQueue }; |
0 commit comments