Math Fundamentals18 sections · 814 units
Open in Course

Unique Paths II - Implementation

(Modified DP with checks)

Here's the full solution:


function uniquePathsWithObstacles(grid)
    m := number of rows in grid
    n := number of columns in grid
    if grid[0][0] = 1 or grid[m - 1][n - 1] = 1 then
        return 0
    dp := 2D array of size m × n, initialized to 0
    dp[0][0] := 1
    // Initialize first column
    for i from 1 to m - 1
        if grid[i][0] = 0 then
            dp[i][0] := dp[i - 1][0]
    // Initialize first row
    for j from 1 to n - 1
        if grid[0][j] = 0 then
            dp[0][j] := dp[0][j - 1]
    // Fill the rest
    for i from 1 to m - 1
        for j from 1 to n - 1
            if grid[i][j] = 0 then
                dp[i][j] := dp[i - 1][j] + dp[i][j - 1]
    return dp[m - 1][n - 1]

You check for obstacles at each cell. If blocked, skip that cell (leave it at 0). If open, sum the paths from above and left. Time: O(m×n)O(m \times n), Space: O(m×n)O(m \times n).