Leetcode–Unique Paths II

The Problem:

Follow up for “Unique Paths”:

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

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

For example,

There is one obstacle in the middle of a 3×3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

Notes:

  1. A basic DP problem, use the exact same approach as in Unique Path, only to mark those 1s to 0 in the path array. Remember that for the first row/column if there is a 1 , then all the subsequent entries should be 0.

Java Solution

  public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] path= new int[m][n];
        boolean blocked = false;
        for(int j = 0; j < n; j++){
            if(obstacleGrid[0][j]==1){
                blocked = true;
            }
            path[0][j] =  blocked? 0: 1;
        }
        blocked = false;
        for(int i = 0; i < m; i++){
            if(obstacleGrid[i][0]==1){
                blocked = true;
            }
            path[i][0] = blocked? 0: 1;
        }
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                 if(obstacleGrid[i][j]==1){
                     path[i][j]=0;
                 }
                 else{
                    path[i][j] = path[i-1][j]+path[i][j-1];
                 }
            }
        }
        return path[m-1][n-1];
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s