leetcode: Recursive 63. Unique Paths II

topic

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

Thinking 

With recursion, is a normal path [i] [j] = path [i] [j-1] + path [i-1] [j],

If the lattice is an obstacle, the path [i] [j] = 0

    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m,n = len(obstacleGrid),len(obstacleGrid[0])
        paths = [[0]*n for i in range(m)]
        for i in range(m):
            for j in range(n):
                
                if i == 0 and j == 0:
                    if obstacleGrid[i][j] == 1:
                        return 0
                    else:
                        paths[i][j] = 1
                elif j == 0:
                    if obstacleGrid[i][j] == 1:
                        paths[i][j] = 0
                    else:
                        paths[i][j] = paths[i-1][j]
                elif i == 0:
                    if obstacleGrid[i][j] == 1:
                        paths[i][j] = 0
                    else:
                        paths[i][j] = paths[i][j-1]
                else:
                    if obstacleGrid[i][j] == 1:
                        paths[i][j] = 0
                    else:
                        paths[i][j] = paths[i-1][j] + paths[i][j-1]
                    
        return paths[m-1][n-1]
                    

 

Published 45 original articles · won praise 1 · views 3365

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104553655