63. Unique Paths II

Explanation:

To solve this problem, we can use dynamic programming. We will create a 2D array to store the number of unique paths to reach each cell. We will initialize the top-left cell with 1 since there is only one way to reach it. Then, we will iterate over the grid, updating the number of paths for each cell based on the cells to the left and above it, considering the obstacle conditions.

Algorithmic Steps:

  1. Initialize a 2D dp array of size m x n to store the number of unique paths to reach each cell.
  2. Initialize the top-left cell of dp to 1.
  3. Iterate over the grid:
    • If the current cell is an obstacle, set the number of paths in dp to 0.
    • Otherwise, update the number of paths in dp based on the cells to the left and above it.
  4. Return the number of unique paths to the bottom-right corner.

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the grid. Space Complexity: O(m * n) for the dp array.

:

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        
        int[][] dp = new int[m][n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else if (i == 0 && j == 0) {
                    dp[i][j] = 1;
                } else {
                    dp[i][j] = (i > 0 ? dp[i - 1][j] : 0) + (j > 0 ? dp[i][j - 1] : 0);
                }
            }
        }
        
        return dp[m - 1][n - 1];
    }
}

Code Editor (Testing phase)

Improve Your Solution

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

  • Add import statement 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.