leecode 解题总结:63. Unique Paths II

本文介绍了一个编程面试题的独特解法,即在网格中寻找从起点到终点的不同路径数量,同时考虑了网格中可能存在障碍物的情况。通过动态规划的方法,文章详细解释了如何初始化边界条件并递推计算每个单元格的路径数。
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
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(障碍物),就设置该元素对应的路径为0来做

输入:
3(行数) 3(列数)
0 0 0
0 1 0
0 0 0

1 3
0 1 0
输出:
2
0

关键:
1 可在计算的时候如果元素为1(障碍物),就设置该元素对应的路径为0来做
初始化第一列,找到从上到下第一个障碍物,将该元素,以及该元素下面元素路径数都要设置为0
同理初始化第一行
*/

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
		if(obstacleGrid.empty())
		{
			return 0;
		}
		int row = obstacleGrid.size();//行数
		int col = obstacleGrid.at(0).size();//列数
		vector< vector<int> > paths(row  , vector<int> (col , 1));
		//初始化第一行和第一列元素,如果对应元素不是障碍物,对应路径数为1,否则为0
		//初始化第一列,找到从上到下第一个障碍物,将该元素,以及该元素下面元素路径数都要设置为0
		int i = 0;
		while(i < row)
		{
			//是障碍物,将该元素以及下面元素路径数都要设置为1
			if( 1 == obstacleGrid.at(i).at(0) )
			{
				while(i < row)
				{
					paths.at(i++).at(0) = 0;
				}
				break;
			}
			else
			{
				i++;
			}
		}
		//初始化第一行
		i = 0;
		while(i < col)
		{
			if( 1 == obstacleGrid.at(0).at(i) )
			{
				while(i < col)
				{
					paths.at(0).at(i++) = 0;
				}
			}
			else
			{
				i++;
			}
		}
		//接下来递推
		for(i = 1 ; i < row ; i++)
		{
			for(int j = 1 ; j < col ; j++)
			{
				if( obstacleGrid.at(i).at(j) != 1)
				{
					paths.at(i).at(j) = paths.at(i).at(j-1) + paths.at(i-1).at(j);
				}
				else
				{
					paths.at(i).at(j) = 0;
				}
			}
		}
		return paths.at(row - 1).at(col - 1);
    }
};


void process()
{
	 vector< vector<int> > nums;
	 int value;
	 int row;
	 int col;
	 Solution solution;
	 while(cin >> row >> col)
	 {
		 nums.clear();
		 for(int i = 0 ; i < row ; i++)
		 {
			 vector<int> num;
			 for(int j = 0 ; j < col; j++)
			 {
				 cin >> value;
				 num.push_back(value); 
			 }
			 nums.push_back(num);
		 }
		 int result = solution.uniquePathsWithObstacles(nums);
		 cout << result << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值