Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1575: Count All Possible Routes

LeetCode 1575 Solution Explanation

Explanation:

To solve this problem, we can use dynamic programming. We define a 3D dp array where dp[i][j][k] represents the number of ways to reach city j with k fuel units starting from city i. We initialize the dp array with base cases where dp[i][finish][0] is set to 1 for all i such that locations[i] == finish.

Next, we iterate over all possible cities, fuel units, and steps remaining. For each step, we calculate the number of ways to reach the current city with the current fuel units by considering all possible transitions from the previous cities with the remaining fuel units. We update the dp array accordingly.

Finally, the answer will be the sum of dp[start][finish][0] to dp[start][finish][fuel] modulo 10^9 + 7. :

LeetCode 1575 Solutions in Java, C++, Python

class Solution {
    public int countRoutes(int[] locations, int start, int finish, int fuel) {
        int n = locations.length;
        int MOD = 1000000007;
        
        int[][][] dp = new int[n][n][fuel + 1];
        for (int i = 0; i < n; i++) {
            if (i != finish) {
                dp[i][finish][0] = 1;
            }
        }
        
        for (int f = 0; f <= fuel; f++) {
            for (int s = 0; s < n; s++) {
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (i != j && f >= Math.abs(locations[i] - locations[j])) {
                            dp[i][s][f] = (dp[i][s][f] + dp[j][s][f - Math.abs(locations[i] - locations[j])]) % MOD;
                        }
                    }
                }
            }
        }
        
        int result = 0;
        for (int f = 0; f <= fuel; f++) {
            result = (result + dp[start][start][f]) % MOD;
        }
        
        return result;
    }
}

Interactive Code Editor for LeetCode 1575

Improve Your LeetCode 1575 Solution

Use the editor below to refine the provided solution for LeetCode 1575. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems