Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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 empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:

Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right
import numpy as np
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        if len(obstacleGrid)==0:
            return 0
        m=len(obstacleGrid)
        example=obstacleGrid[0]
        if len(example)==0:
            return 0
        n=len(example)
        if m==1 and n==1:
            if obstacleGrid[0][0]==0:
                return 1
            else:
                return 0
        self.m=m
        self.n=n
        self.matrix=np.zeros([m,n])-1
        #print(self.matrix)
        count=self.check_path(1,1,obstacleGrid)
        return int(count)
    def check_path(self,i,j,obstacle):
        
        if i==self.m and j==self.n:
            return 0
       
        if i==self.m:
            label=True
            for k in range(j-1,self.n):
                if obstacle[i-1][k]==1:
                    label=False
            if label:
                return 1
            else:
                return 0
        if j==self.n:
            label=True
            for k in range(i-1,self.m):
                if obstacle[k][j-1]==1:
                    label=False
            if label:
                return 1
            else:
                return 0
        if self.matrix[i-1][j-1]!=-1:
            return self.matrix[i-1][j-1]
        if obstacle[i-1][j-1]==1:
            self.matrix[i-1][j-1]=0
            return 0
        if obstacle[i-1][j]==0:
            count1=self.check_path(i,j+1,obstacle)
        else:
            count1=0
        if obstacle[i][j-1]==0:
            count2=self.check_path(i+1,j,obstacle)
        else:
            count2=0
        self.matrix[i-1][j-1]=count1+count2   
        return self.matrix[i-1][j-1]
        

Solution: https://leetcode.com/problems/unique-paths-ii/