题目: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.
思路:动态规划
本题不是特别的难,只需要判断下是否空格为1,如果为1,则sum为0,不是1的话,那么就和第一题一样。
代码:
class Solution { public: //https://leetcode.com/problems/unique-paths-ii/ int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { const int m=obstacleGrid.size(),n=obstacleGrid[0].size(); if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1){ return 0; } int sum[m][n]; sum[0][0]=1; for(int i=1;i<n;i++){ sum[0][i]=obstacleGrid[0][i]==0?sum[0][i-1]:0; }//如果等于1,直接为0;如果不为1,和前面相同 for(int i=1;i<m;i++){ sum[i][0]=obstacleGrid[i][0]==0?sum[i-1][0]:0; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ sum[i][j] = obstacleGrid[i][j]==0?(sum[i-1][j]+sum[i][j-1]):0; } } return sum[m-1][n-1]; } };