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.
1#include <iostream>
2#include <vector>
3#include <cstring>
4
5using namespace std;
6
7const int MOD = 1000000007;
8
9int dp[101][201];
10
11int countRoutesUtil(vector<int> &locations, int curr, int finish, int fuel) {
12 if (fuel < 0) return 0;
13 if (dp[curr][fuel] != -1) return dp[curr][fuel];
14
15 int result = (curr == finish) ? 1 : 0;
16 for (int i = 0; i < locations.size(); ++i) {
17 if (i != curr) {
18 result = (result + countRoutesUtil(locations, i, finish, fuel - abs(locations[i] - locations[curr]))) % MOD;
19 }
20 }
21 return dp[curr][fuel] = result;
22}
23
24int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
25 memset(dp, -1, sizeof(dp));
26 return countRoutesUtil(locations, start, finish, fuel);
27}
28
29int main() {
30 vector<int> locations = {2, 3, 6, 8, 4};
31 int start = 1, finish = 3, fuel = 5;
32 cout << countRoutes(locations, start, finish, fuel) << endl; // Output: 4
33 return 0;
34}
This C++ solution employs a similar approach to the C solution with a vector of locations and recursive calculation of routes using memoization. The dp table is initialized with -1 and stores the subproblems' results.
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.