source: https://leetcode.com/problems/count-all-possible-routes/
Count All Possible Routes
Description
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] – locations[j]|. Please notice that |x| denotes the absolute value of x.
Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).
Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
Explanation: The following are all possible routes; each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3
Example 2:
Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
Explanation: The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
Example 3:
Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
Constraints:
- 2 <= locations.length <= 100
- 1 <= locations[i] <= 109
- All integers in locations are distinct.
- 0 <= start, finish < locations.length
- 1 <= fuel <= 200
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Solution { private static final int MOD = 1_000_000_007; public int countRoutes(int[] locations, int start, int finish, int fuel) { int n = locations.length; int[][] cost = new int[n][n]; Integer[][] memo = new Integer[n+1][fuel+1]; for(int i=0;i<locations.length;i++){ for(int j=i+1;j<locations.length;j++){ int c = Math.abs(locations[i] - locations[j]); cost[i][j] = c; cost[j][i] = c; } } return dfs(locations, cost, start, finish, fuel, memo); } private int dfs(int[] locations, int[][] cost, int currIndex, int finish, int fuel, Integer[][] memo){ int count = 0; if(finish==currIndex){ count = count +1; } if(memo[currIndex][fuel]!=null){ return memo[currIndex][fuel]; } for(int nextIndex=0;nextIndex<locations.length;nextIndex++){ if(nextIndex!=currIndex && cost[currIndex][nextIndex] <= fuel){ count = ((count)%MOD + (dfs(locations, cost, nextIndex, finish, fuel - cost[currIndex][nextIndex], memo))%MOD)%MOD; } } memo[currIndex][fuel] = count; return count; } } |