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.
此题是前篇Unique Paths 的变形。加入了障碍格子。但是思路与前篇基本一致,只是在前篇的基础上考虑了障碍格子。变化的地方有两个:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { //c++ int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); int array[m][n]; //init bool haveObs = false; for(int i = 0; i < n; i++){ if(obstacleGrid[0][i] == 0 && !haveObs){ array[0][i] = 1; continue; } else if(obstacleGrid[0][i] == 1){ haveObs = true; } array[0][i] = 0; } haveObs = false; for(int i = 0; i < m; i++) { if(obstacleGrid[i][0] == 0 && !haveObs){ array[i][0] = 1; continue; } else if(obstacleGrid[i][0 ==1]){ haveObs = true; } array[i][0] = 0; } for(int i = 1; i < m; i++) for(int j = 1; j < n; j++){ array[i][j] = 0; if(obstacleGrid[i][j] == 1) continue; if(obstacleGrid[i-1][j] == 0) array[i][j] += array[i-1][j]; if(obstacleGrid[i][j-1] == 0) array[i][j] +=array[i][j-1]; } return array[m-1][n-1]; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/40897285