Leetcode 63. Unique Paths II

Problem

A robot is located at the top-left corner of a m x n grid and trying to reach the bottom-right corner of the grid. The robot can only move either down or right at any point in time and there are some block can not be reached. How many possible unique paths are there?

Algorithm

Using dynamic programming to solve:
f ( i , j ) = f ( i − 1 , j ) + f ( i , j − 1 ) f(i, j) = f(i-1, j) + f(i, j-1) f(i,j)=f(i1,j)+f(i,j1)
if the block can not be reached:
f ( i , j ) = 0 f(i, j) = 0 f(i,j)=0

Code

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        if not obstacleGrid:
            return 0
        row = len(obstacleGrid)
        if not row:
            return 0
        col = len(obstacleGrid[0])
        if not col:
            return 0
        step = [[0] * col for _ in range(row)]
        
        if not obstacleGrid[0][0]:
            step[0][0] = 1
        for i in range(row):
            for j in range(col):
                if i or j:
                    step[i][j] = 0
                if not obstacleGrid[i][j]:
                    if i:
                        step[i][j] += step[i-1][j]
                    if j:
                        step[i][j] += step[i][j-1]
        
        return step[row-1][col-1]

你可能感兴趣的:(解题报告)