|
| 1 | +/** |
| 2 | + * 1976. Number of Ways to Arrive at Destination |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional |
| 7 | + * roads between some intersections. The inputs are generated such that you can reach any |
| 8 | + * intersection from any other intersection and that there is at most one road between any two |
| 9 | + * intersections. |
| 10 | + * |
| 11 | + * You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means |
| 12 | + * that there is a road between intersections ui and vi that takes timei minutes to travel. You |
| 13 | + * want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the |
| 14 | + * shortest amount of time. |
| 15 | + * |
| 16 | + * Return the number of ways you can arrive at your destination in the shortest amount of time. |
| 17 | + * Since the answer may be large, return it modulo 109 + 7. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number} n |
| 22 | + * @param {number[][]} roads |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var countPaths = function(n, roads) { |
| 26 | + const MOD = 1e9 + 7; |
| 27 | + const graph = Array.from({ length: n }, () => []); |
| 28 | + const distances = new Array(n).fill(Infinity); |
| 29 | + const ways = new Array(n).fill(0); |
| 30 | + |
| 31 | + for (const [u, v, time] of roads) { |
| 32 | + graph[u].push([v, time]); |
| 33 | + graph[v].push([u, time]); |
| 34 | + } |
| 35 | + |
| 36 | + const queue = [[0, 0]]; |
| 37 | + distances[0] = 0; |
| 38 | + ways[0] = 1; |
| 39 | + |
| 40 | + while (queue.length) { |
| 41 | + const [dist, node] = queue.shift(); |
| 42 | + |
| 43 | + if (dist > distances[node]) continue; |
| 44 | + |
| 45 | + for (const [next, time] of graph[node]) { |
| 46 | + const newDist = dist + time; |
| 47 | + |
| 48 | + if (newDist < distances[next]) { |
| 49 | + distances[next] = newDist; |
| 50 | + ways[next] = ways[node]; |
| 51 | + queue.push([newDist, next]); |
| 52 | + queue.sort((a, b) => a[0] - b[0]); |
| 53 | + } else if (newDist === distances[next]) { |
| 54 | + ways[next] = (ways[next] + ways[node]) % MOD; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return ways[n - 1]; |
| 60 | +}; |
0 commit comments