LeetCode 63. Unique Paths II (javascript solution)

cod3pineapple

codingpineapple

Posted on April 25, 2021

LeetCode 63. Unique Paths II
(javascript solution)

Description:

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and space is marked as 1 and 0 respectively in the grid.

How many possible unique paths are there?

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n^2)

var uniquePathsWithObstacles = function(obstacleGrid) {
    const m = obstacleGrid.length;
    const n = obstacleGrid[0].length
    // Create dp array
    const dp = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
    dp[0][1] = 1

    for(let i = 1; i < m+1; i++) {
        for(let j = 1; j < n+1; j++){
            // Add value to dp array if the cell we are looking at in the grid is not blocked
            dp[i][j] = obstacleGrid[i-1][j-1]===0 ? dp[i-1][j]+dp[i][j-1] : 0 
        }
    }
    return dp[m][n]
};
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
cod3pineapple
codingpineapple

Posted on April 25, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related