|
| 1 | +/** |
| 2 | + * Title: Number of Restricted Paths from First to Last Node |
| 3 | + * Description: There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 04/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number} n |
| 10 | + * @param {number[][]} edges |
| 11 | + * @return {number} |
| 12 | + */ |
| 13 | +var countRestrictedPaths = function (n, edges) { |
| 14 | + const g = Array.from({ length: n + 1 }, () => []); |
| 15 | + for (let [a, b, c] of edges) { |
| 16 | + g[a].push([b, c]); |
| 17 | + g[b].push([a, c]); |
| 18 | + } |
| 19 | + // do dijkstras to find shortest path from n to all nodes |
| 20 | + const dis = new Array(n + 1).fill(Infinity); |
| 21 | + dis[n] = 0; |
| 22 | + const dijkstra = () => { |
| 23 | + const heap = new MinPriorityQueue({ priority: (x) => x[1] }); |
| 24 | + heap.enqueue([n, 0]); |
| 25 | + while (heap.size()) { |
| 26 | + const [node, cost] = heap.dequeue().element; |
| 27 | + for (let [nextNode, w] of g[node]) { |
| 28 | + const totalCost = cost + w; |
| 29 | + if (dis[nextNode] > totalCost) { |
| 30 | + dis[nextNode] = totalCost; |
| 31 | + heap.enqueue([nextNode, totalCost]); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + }; |
| 36 | + dijkstra(); |
| 37 | + |
| 38 | + // do dfs from 1 having path always lesser dist |
| 39 | + let rPaths = 0; |
| 40 | + const MOD = 1000000007; |
| 41 | + const dp = new Array(n + 1).fill(-1); |
| 42 | + const dfs = (curr = 1, rCost = dis[1]) => { |
| 43 | + if (curr == n) return 1; |
| 44 | + if (dp[curr] != -1) return dp[curr]; |
| 45 | + |
| 46 | + let op = 0; |
| 47 | + for (let [n, w] of g[curr]) { |
| 48 | + if (dis[n] < rCost) { |
| 49 | + op = (op + dfs(n, dis[n])) % MOD; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return (dp[curr] = op); |
| 54 | + }; |
| 55 | + return dfs(); |
| 56 | +}; |
0 commit comments