Unique Paths II
Total Accepted: 35061 Total Submissions: 125276My Submissions
Question Solution
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.
Hide Tags
这道题只是在前面62题的基础上加了路障,也很简单,就是在路障这个地方就把它的路径的个数直接设为0
就好了,其它的和62题没啥区别
#include<iostream> #include <vector> using namespace std; int uniquePathsWithObstacles(vector<vector<int> >& obstacleGrid) { if(obstacleGrid.empty()) return 0; int m=obstacleGrid.size(); int n=obstacleGrid[0].size(); int **ary1; ary1=new int *[m]; for(int i=0;i<m;i++) ary1[i]=new int[n]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) ary1[i][j]=obstacleGrid[i][j]-1; for(int i=m-1;i>=0;i--) for(int j=n-1;j>=0;j--) if(ary1[i][j]!=0) { if(i==m-1&&j==n-1) ary1[i][j]=1; else if(i==m-1&&j<n-1) ary1[i][j]=ary1[i][j+1]; else if(i<m-1&&j==n-1) ary1[i][j]=ary1[i+1][j]; else ary1[i][j]=ary1[i+1][j]+ary1[i][j+1]; } int last_result=ary1[0][0]; for(int i=0;i<m;i++) delete[]ary1[i]; delete[]ary1; return last_result; } int main() { }
时间: 2024-08-01 20:32:37