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
这道题容易少考虑几种形式:
1.起点就是障碍
2.当第一行或者第一列某一点存在障碍,那么这一行或一列之后都是无法到达.
3.本题最初用1表示障碍,0表示可行,但在计算时候我们一般会反过来.这时候只需用1 - obstacleGrid[i][j]表达即可.
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if obstacleGrid[0][0] == 1: return 0
r,c = len(obstacleGrid), len(obstacleGrid[0])
dp = [[1 for _ in range(c)] for _ in range(r)]
for i in range(1, r):
dp[i][0] = dp[i - 1][0] * (1 - obstacleGrid[i][0])
for i in range(1, c):
dp[0][i] = dp[0][i - 1] * (1 - obstacleGrid[0][i])
for i in range(1, r):
for j in range(1, c):
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * (1 - obstacleGrid[i][j])
return(dp[-1][-1])
还有更为简洁的in place算法
def uniquePathsWithObstacles(self, obstacleGrid):
if not obstacleGrid:
return
r, c = len(obstacleGrid), len(obstacleGrid[0])
obstacleGrid[0][0] = 1 - obstacleGrid[0][0]
for i in xrange(1, r):
obstacleGrid[i][0] = obstacleGrid[i-1][0] * (1 - obstacleGrid[i][0])
for i in xrange(1, c):
obstacleGrid[0][i] = obstacleGrid[0][i-1] * (1 - obstacleGrid[0][i])
for i in xrange(1, r):
for j in xrange(1, c):
obstacleGrid[i][j] = (obstacleGrid[i-1][j] + obstacleGrid[i][j-1]) * (1 - obstacleGrid[i][j])
return obstacleGrid[-1][-1]