|
| 1 | +/** |
| 2 | + * 1575. Count All Possible Routes |
| 3 | + * https://leetcode.com/problems/count-all-possible-routes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of distinct positive integers locations where locations[i] represents |
| 7 | + * the position of city i. You are also given integers start, finish and fuel representing the |
| 8 | + * starting city, ending city, and the initial amount of fuel you have, respectively. |
| 9 | + * |
| 10 | + * At each step, if you are at city i, you can pick any city j such that j != i and |
| 11 | + * 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the |
| 12 | + * amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes |
| 13 | + * the absolute value of x. |
| 14 | + * |
| 15 | + * Notice that fuel cannot become negative at any point in time, and that you are allowed to visit |
| 16 | + * any city more than once (including start and finish). |
| 17 | + * |
| 18 | + * Return the count of all possible routes from start to finish. Since the answer may be too large, |
| 19 | + * return it modulo 109 + 7. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} locations |
| 24 | + * @param {number} start |
| 25 | + * @param {number} finish |
| 26 | + * @param {number} fuel |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var countRoutes = function(locations, start, finish, fuel) { |
| 30 | + const MOD = 1e9 + 7; |
| 31 | + const memo = new Array(locations.length).fill().map(() => new Array(fuel + 1).fill(-1)); |
| 32 | + |
| 33 | + function calculateRoutes(currentCity, remainingFuel) { |
| 34 | + if (remainingFuel < 0) return 0; |
| 35 | + if (memo[currentCity][remainingFuel] !== -1) return memo[currentCity][remainingFuel]; |
| 36 | + |
| 37 | + let routes = currentCity === finish ? 1 : 0; |
| 38 | + |
| 39 | + for (let nextCity = 0; nextCity < locations.length; nextCity++) { |
| 40 | + if (nextCity !== currentCity) { |
| 41 | + const fuelCost = Math.abs(locations[currentCity] - locations[nextCity]); |
| 42 | + routes = (routes + calculateRoutes(nextCity, remainingFuel - fuelCost)) % MOD; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + memo[currentCity][remainingFuel] = routes; |
| 47 | + return routes; |
| 48 | + } |
| 49 | + |
| 50 | + return calculateRoutes(start, fuel); |
| 51 | +}; |
0 commit comments