[LeetCode]_63 Unique Paths II

一、题目描述

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

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.

大体意思:

机器人从star 到黄色星星标注的点,一共找到多少种路径。

rule:

机器人只能往下面或者往后面走。

每个方格内存放一个数字,如果是0则表示方格可以通过如果为1表示方格上面有障碍物不能通过。

二解题思路及代码

首先确定问题的性质,到达黄色星星的路径个数,仅与到达黄色星星上面的路径数目与到达黄色星星左边路径数目有关。

当前状态仅与前面的有限个状态有关。

决定用动态规划的思想。

定义状态:store[i][j]//表示到达i行j 列的路径

状态转移方程:store[i][j]=store[i-1][j]+store[i][j-1]//当前路径数等于到达左边路径数目加上到达后面路径数目

对特殊情况考虑:

当前方格取值为1:

则当前到达当前方格没有路径,用sotre[i][j]=-5表示没有路径

当前方格取值为0:

查看store[i-1][j]与sotre[i][j-1]状态

只有当sotre[i-1][j]方格为0并且sotre[i-1][j]有路径的时候才可以取出当前值

如果不满足条件则代表到达i-1,j的路径数为0

有如下表达式:

int a =(obstacleGrid[i-1][j]==0&&store[i-1][j]!=-5)?store[i-1][j]:0;
int b=(obstacleGrid[i][j-1]==0&&store[i][j-1]!=-5)?store[i][j-1]:0;
store[i][j]=a+b;
if(store[i][j]==0)
{
store[i][j]=-5;
}

完整程序代码:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {

int row=obstacleGrid.size();
int colu=obstacleGrid[0].size();
vector<vector<int>> store(row,vector<int>(colu,0));
int i,j;//用于进行循环遍历
for(i=0;i<colu;i++)
{
if(obstacleGrid[0][i]==0)

{
store[0][i]=1;
}
else{break;}

}
for(;i<colu;i++)
{
store[0][i]==-5;
}

for(j=0;j<row;j++)
{
if(obstacleGrid[j][0]==0)

{
store[j][0]=1;
}
else{
break;}
}
for(;j<row;j++)
{
store[j][0]=-5;
}
for(i=1;i<row;i++)
{
for(j=1;j<colu;j++)
{

if(obstacleGrid[i][j]==1)
{
store[i][j]=-5;
continue;
}
int a =(obstacleGrid[i-1][j]==0&&store[i-1][j]!=-5)?store[i-1][j]:0;
int b=(obstacleGrid[i][j-1]==0&&store[i][j-1]!=-5)?store[i][j-1]:0;
store[i][j]=a+b;
if(store[i][j]==0)
{
store[i][j]=-5;
}
}

}
if(store[row-1][colu-1]==-5)
{
return 0;
}
return store[row-1][colu-1];



}
};

三、题目总结

在初始化的时候忽略了一种情况,当第一行或第一列某个位置出现1以后,后面所有的方格都将没有路径。

猜你喜欢

转载自www.cnblogs.com/zydxx/p/9970889.html
今日推荐