|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to solve the problem with dynamic programming |
| 4 | + int solve(vector<int>& obstacles, int currlane, int currpos) { |
| 5 | + int n = obstacles.size() - 1; // The last position in the obstacles array |
| 6 | + // If we have reached the last position, no more jumps are needed |
| 7 | + if(currpos == n) return 0; |
| 8 | + |
| 9 | + // If the next position is not blocked by the current lane |
| 10 | + if(obstacles[currpos + 1] != currlane) { |
| 11 | + return solve(obstacles, currlane, currpos + 1); // Move to the next position without jumping |
| 12 | + } else { |
| 13 | + int ans = INT_MAX; // Initialize the answer to a large value (to minimize later) |
| 14 | + // Try all 3 lanes (1, 2, 3) to check for the minimum jumps |
| 15 | + for(int i = 1; i <= 3; i++) { |
| 16 | + // If the current lane is not the one we're trying, and the next lane is not blocked |
| 17 | + if(currlane != i && obstacles[currpos] != i) { |
| 18 | + // Recursively solve the problem, with one additional jump (1 +) |
| 19 | + ans = min(ans, 1 + solve(obstacles, i, currpos)); |
| 20 | + } |
| 21 | + } |
| 22 | + return ans; // Return the minimum number of jumps found |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // Main function to return the minimum number of side jumps |
| 27 | + int minSideJumps(vector<int>& obstacles) { |
| 28 | + return solve(obstacles, 2, 0); // Start from lane 2 and position 0 (the first obstacle) |
| 29 | + } |
| 30 | +}; |
0 commit comments