Sponsored
Sponsored
This approach involves using dynamic programming to keep track of the number of ways to reach the target city with the available fuel. We will define a DP table where dp[i][f] represents the number of ways to start from city i with f units of fuel left and reach the target city. We recursively fill this table while considering moves to any other city and subtracting the appropriate fuel cost for that move. The result will be stored in the dp[start][fuel] after exploring all possible routes.
Time Complexity: O(n * fuel * n), where n is the number of cities. This can be reduced using better states or pruning.
Space Complexity: O(n * fuel) for the dp table.
1const MOD = 1000000007;
2
3var countRoutes = function(locations, start, finish, fuel) {
4 const dp = Array.from({ length: locations.length }, () => Array(fuel + 1).fill(-1));
5 const countRoutesUtil = (current, fuelLeft) => {
6 if (fuelLeft < 0) return 0;
7 if (dp[current][fuelLeft] !== -1) return dp[current][fuelLeft];
8
9 let result = (current === finish) ? 1 : 0;
10 for (let i = 0; i < locations.length; i++) {
11 if (i !== current) {
12 result = (result + countRoutesUtil(i, fuelLeft - Math.abs(locations[i] - locations[current]))) % MOD;
13 }
14 }
15
16 dp[current][fuelLeft] = result;
17 return result;
18 };
19
20 return countRoutesUtil(start, fuel);
21};
22
23const locations = [2, 3, 6, 8, 4];
24const start = 1;
25const finish = 3;
26const fuel = 5;
27console.log(countRoutes(locations, start, finish, fuel)); // Output: 4
This JavaScript solution initializes a memoization table and recursively evaluates potential paths, considering fuel constraints. Results are stored and retrieved from the dp array, ensuring efficiency and accuracy with each recursive step.
In this approach, a depth-first search (DFS) is implemented to explore possible routes from the start to the finish city. Each travel option is a branch in the DFS tree, where the algorithm explores each choice of stopping at a different city until it no longer has fuel. The recursion keeps track of current fuel and updates the count whenever it reaches the finish city with valid fuel.
Time Complexity: O(n^fuel) without pruning, given recursive branching per city. This complexity is potentially high without memoization.
Space Complexity: O(fuel) due to recursive call stack depth.
The Python version follows the DFS model traversing each potential path recursively. Without memoization, this may lead to computational redundancy but provides clear path evaluations.