#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;
}