1. Unique Paths (Leetcode Number: 62)
While initializing the array, all the values of the first row as well as the first column are 1 as the solution is unique.
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
i, j = 0, 0
dp = [ [1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
2. Unique Paths II (Leetcode Number: 63)
The values of the first column elements and first row elements need to be flipped (0 - > 1 and 1 -> 0). The original 1 means there is an obstacle, after being converted to 0, it means the number of the paths to this grid is 0 as it's blocked. So this grid wouldn't be a part of the calculation of possible paths for next grid.
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
row = len(obstacleGrid)
col = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1:
return 0
obstacleGrid[0][0] = 1
for i in range(1, row):
obstacleGrid[i][0] = int(obstacleGrid[i][0] == 0 and obstacleGrid[i -1 ][0] == 1)
for j in range(1, col):
obstacleGrid[0][j] = int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j - 1])
for i in range(1, row):
for j in range(1, col):
if obstacleGrid[i][j] == 0:
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]
else:
obstacleGrid[i][j] = 0
return obstacleGrid[row - 1][col - 1]