[LeetCode] Count All Possible Routes

1575. Count All Possible Routes

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 10^9 + 7.

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
class Solution {
int dp[101][201];
int mod = 1e9 + 7;
int solution(vector<int>& lo, int cur, int dst, int fuel) {
if(dp[cur][fuel] != -1) return dp[cur][fuel];
int& res = dp[cur][fuel] = cur == dst;

for(int i = cur + 1; i < lo.size() and abs(lo[i] - lo[cur]) <= fuel; i++) {
res = (res + solution(lo, i, dst, fuel - lo[i] + lo[cur])) % mod;
}

for(int i = cur - 1; i >= 0 and abs(lo[i] - lo[cur]) <= fuel; i--) {
res = (res + solution(lo, i, dst, fuel - lo[cur] + lo[i])) % mod;
}

return res;
}
public:
int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
memset(dp,-1,sizeof(dp));
int st = locations[start], fin = locations[finish];
sort(locations.begin(), locations.end());
start = lower_bound(locations.begin(), locations.end(), st) - locations.begin();
finish = lower_bound(locations.begin(), locations.end(), fin) - locations.begin();
return solution(locations, start, finish, fuel);
}

};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/count-all-possible-routes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.