题目:
Follow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
代码:oj测试通过 Runtime: 48 ms
1 class Solution: 2 # @param obstacleGrid, a list of lists of integers 3 # @return an integer 4 def uniquePathsWithObstacles(self, obstacleGrid): 5 # ROW & COL 6 ROW = len(obstacleGrid) 7 COL = len(obstacleGrid[0]) 8 # one row case 9 if ROW==1: 10 for i in range(COL): 11 if obstacleGrid[0][i]==1: 12 return 0 13 return 1 14 # one column case 15 if COL==1: 16 for i in range(ROW): 17 if obstacleGrid[i][0]==1: 18 return 0 19 return 1 20 # visit normal case 21 dp = [[0 for i in range(COL)] for i in range(ROW)] 22 for i in range(COL): 23 if obstacleGrid[0][i]!=1: 24 dp[0][i]=1 25 else: 26 break 27 for i in range(ROW): 28 if obstacleGrid[i][0]!=1: 29 dp[i][0]=1 30 else: 31 break 32 # iterator the other nodes 33 for row in range(1,ROW): 34 for col in range(1,COL): 35 if obstacleGrid[row][col]==1: 36 dp[row][col]=0 37 else: 38 dp[row][col]=dp[row-1][col]+dp[row][col-1] 39 40 return dp[ROW-1][COL-1]
思路:
思路模仿Unique Path这道题:
http://www.cnblogs.com/xbf9xbf/p/4250359.html
只不过多了某些障碍点;针对障碍点,加一个判断条件即可:如果遇上障碍点,那么到途径这个障碍点到达终点的可能路径数为0。然后继续迭代到尾部即可。
个人感觉40行的python脚本不够简洁,总是把special case等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。