码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_63题——Unique Paths II(动态规划)

时间:2015-06-02 16:48:50      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

Unique Paths II

 Total Accepted: 35061 Total Submissions: 125276My Submissions

 

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
 Array Dynamic Programming
 
       这道题只是在前面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()
{

}

  

leetcode_63题——Unique Paths II(动态规划)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4546681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!