|
| 1 | +/** |
| 2 | + * Title: Network Delay Time |
| 3 | + * Description: You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 04/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number[][]} times |
| 10 | + * @param {number} n |
| 11 | + * @param {number} k |
| 12 | + * @return {number} |
| 13 | + */ |
| 14 | + |
| 15 | +//min heap Class using array and sort let's assume that TC:log(n) |
| 16 | +class Minheap { |
| 17 | + heap = []; |
| 18 | + constructor(val) { |
| 19 | + this.heap.push(val); |
| 20 | + } |
| 21 | + size() { |
| 22 | + return this.heap.length; |
| 23 | + } |
| 24 | + heapify() { |
| 25 | + this.heap.sort((a, b) => b[0] - a[0]); |
| 26 | + } |
| 27 | + push(val) { |
| 28 | + this.heap.push(val); |
| 29 | + } |
| 30 | + pop() { |
| 31 | + return this.heap.pop(); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +var networkDelayTime = function (times, n, k) { |
| 36 | + //create Ajececy list |
| 37 | + const graph = {}; |
| 38 | + for (let i = 1; i <= n; i++) graph[i] = []; |
| 39 | + for (let [s, d, w] of times) graph[s].push([w, d]); |
| 40 | + |
| 41 | + const visited = new Set(); |
| 42 | + const heap = new Minheap([0, k]); |
| 43 | + let t = 0; |
| 44 | + |
| 45 | + //while our heap is not empy |
| 46 | + while (heap.size() > 0) { |
| 47 | + const [w, n] = heap.pop(); |
| 48 | + if (visited.has(n)) continue; |
| 49 | + |
| 50 | + visited.add(n); |
| 51 | + t = Math.max(t, w); |
| 52 | + |
| 53 | + // Start BFS traversal |
| 54 | + for (let [w1, n1] of graph[n]) { |
| 55 | + if (visited.has(n1)) continue; |
| 56 | + heap.push([w1 + w, n1]); |
| 57 | + } |
| 58 | + |
| 59 | + heap.heapify(); |
| 60 | + } |
| 61 | + |
| 62 | + return visited.size === n ? t : -1; |
| 63 | +}; |
0 commit comments