|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function with memoization to solve the problem |
| 4 | + int solve(vector<int>& obstacles, int currlane, int currpos, vector<vector<int>>& dp) { |
| 5 | + int n = obstacles.size() - 1; // Last position in the obstacles array |
| 6 | + |
| 7 | + // Base case: If we have reached the last position, no more jumps are needed |
| 8 | + if(currpos == n) return 0; |
| 9 | + |
| 10 | + // If this state has already been computed, return the cached result from dp table |
| 11 | + if(dp[currlane][currpos] != -1) return dp[currlane][currpos]; |
| 12 | + |
| 13 | + // If the next position is not blocked by the current lane, move to the next position without jumping |
| 14 | + if(obstacles[currpos + 1] != currlane) { |
| 15 | + return solve(obstacles, currlane, currpos + 1, dp); |
| 16 | + } else { |
| 17 | + int ans = INT_MAX; // Initialize the answer to a large value (for minimization) |
| 18 | + |
| 19 | + // Try all 3 possible lanes (1, 2, 3) and find the minimum side jump |
| 20 | + for(int i = 1; i <= 3; i++) { |
| 21 | + // If the current lane is not the lane we're trying to move to, and the next lane is not blocked |
| 22 | + if(currlane != i && obstacles[currpos] != i) { |
| 23 | + // Recursively calculate the number of jumps, adding 1 for the jump |
| 24 | + ans = min(ans, 1 + solve(obstacles, i, currpos, dp)); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // Store the result in the dp table to avoid recomputation and return the answer |
| 29 | + return dp[currlane][currpos] = ans; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Main function to return the minimum number of side jumps |
| 34 | + int minSideJumps(vector<int>& obstacles) { |
| 35 | + int n = obstacles.size(); // Get the size of the obstacles array |
| 36 | + |
| 37 | + // Initialize the dp table with -1 (indicating uncomputed states) |
| 38 | + // dp[i][j] represents the minimum jumps needed from lane i at position j |
| 39 | + vector<vector<int>> dp(4, vector<int>(n - 1, -1)); |
| 40 | + |
| 41 | + // Start from lane 2 and position 0, then call the recursive solve function |
| 42 | + return solve(obstacles, 2, 0, dp); |
| 43 | + } |
| 44 | +}; |
0 commit comments