标签:
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.
Array Dynamic Programming
#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()
{
}
leetcode_63题——Unique Paths II(动态规划)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4546681.html