-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathCount All Possible Routes.java
60 lines (40 loc) · 1.55 KB
/
Count All Possible Routes.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Runtime: 81 ms (Top 78.44%) | Memory: 41.8 MB (Top 95.21%)
/*
Using DFS and Memo :
1. We will start from start pos provided and will dfs travel to each other location .
2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling
3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path
4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing .
*/
class Solution {
int mod = (int)Math.pow(10,9) + 7 ;
int[][] dp ;
public int countRoutes(int[] locations, int start, int finish, int fuel) {
dp = new int[locations.length][fuel+1] ;
for(int[] row : dp){
Arrays.fill(row , -1) ;
}
return dfs(locations , start , finish , fuel);
}
public int dfs(int[] locations , int cur_location , int finish , int fuel){
if(fuel < 0){
return 0 ;
}
if(dp[cur_location][fuel] != -1){
return dp[cur_location][fuel] ;
}
int result = 0 ;
if(cur_location == finish){
result++ ;
}
for(int i=0 ; i<locations.length ; i++){
if(i == cur_location) continue ;
int fuel_cost = Math.abs(locations[i] - locations[cur_location]);
int next_trip = dfs(locations , i , finish , fuel-fuel_cost);
result += next_trip ;
result %= mod ;
}
dp[cur_location][fuel] = result ;
return dp[cur_location][fuel] ;
}
}