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
.
思路:整体思路和Unique Paths一致,就是当a[i][j]=1时,b[i][j]=0,而不是b[i-1][j]+b[i][j-1]。注意初始化a[i][0]和a[0][i]时,只要第一行或者第一列中出现了障碍物,那么就不可能再接着向右走与向下走了。所以要这样初始化:首先初始化b[0][0],如果a[0][0]=1,那么b[0][0]=0,否则为1。后面继续设置a[][]
class Solution { private: int b[101][101]; public: int uniquePathsWithObstacles(vector<vector<int>>& a) { int i,j; int row=a.size(); int col=a[0].size(); b[0][0]= a[0][0]==1? 0:1; for(i=1;i<row;i++) b[i][0]= a[i][0]==1? 0:b[i-1][0]; for(i=1;i<col;i++) b[0][i]= a[0][i]==1? 0:b[0][i-1]; for(i=1;i<row;i++){ for(j=1;j<col;j++){ b[i][j]= a[i][j]==1? 0:b[i-1][j]+b[i][j-1]; } } return b[row-1][col-1]; } };