|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Function to solve the problem using dynamic programming |
| 4 | + int solve(vector<int>& obstacles) { |
| 5 | + int n = obstacles.size() - 1; // Get the last position in the obstacles array |
| 6 | + // Initialize the dp table with large values (1e9), where dp[lane][pos] represents the minimum jumps required |
| 7 | + // to reach the end from position 'pos' in 'lane'. |
| 8 | + vector<vector<int>> dp(4, vector<int>(n + 1, 1e9)); |
| 9 | + |
| 10 | + // Base case: at the last position (n), no more jumps are needed, hence 0 jumps for all lanes |
| 11 | + dp[0][n] = 0; |
| 12 | + dp[1][n] = 0; |
| 13 | + dp[2][n] = 0; |
| 14 | + dp[3][n] = 0; |
| 15 | + |
| 16 | + // Iterate from the second-last position to the start of the array |
| 17 | + for(int pos = n - 1; pos >= 0; pos--) { |
| 18 | + // Try all 3 lanes (1, 2, 3) for each position |
| 19 | + for(int lane = 1; lane <= 3; lane++) { |
| 20 | + |
| 21 | + // If the next position is not blocked by the current lane, no jump is needed |
| 22 | + if(obstacles[pos + 1] != lane) { |
| 23 | + dp[lane][pos] = dp[lane][pos + 1]; // Carry over the result from the next position |
| 24 | + } else { |
| 25 | + // If the next position is blocked, we need to jump to a different lane |
| 26 | + int ans = 1e9; // Initialize the answer to a large value (to minimize later) |
| 27 | + |
| 28 | + // Try all 3 possible lanes (1, 2, 3) to find the best jump option |
| 29 | + for(int i = 1; i <= 3; i++) { |
| 30 | + // If the current lane is not the lane we're trying to jump to, and the lane is not blocked |
| 31 | + if(lane != i && obstacles[pos] != i) { |
| 32 | + // Add 1 for the jump and update the answer with the minimum jumps required |
| 33 | + ans = min(ans, 1 + dp[i][pos + 1]); |
| 34 | + } |
| 35 | + } |
| 36 | + dp[lane][pos] = ans; // Store the result for this position and lane |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Return the minimum jumps required starting from position 0 with lane 2. |
| 42 | + // We also consider the case where we might need one jump to lane 1 or lane 3. |
| 43 | + return min({dp[2][0], dp[1][0] + 1, dp[3][0] + 1}); |
| 44 | + } |
| 45 | + |
| 46 | + // Main function to return the minimum number of side jumps |
| 47 | + int minSideJumps(vector<int>& obstacles) { |
| 48 | + return solve(obstacles); // Call the solve function to get the result |
| 49 | + } |
| 50 | +}; |
0 commit comments