题目如下:
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.
分析如下:
采用和上一题 Unique Path类似的思路(思路一,动态规划),额外增加一个条件判断:如果obstacleGrid[i][j]==1,则说明有障碍,不能在(i,j)点累计路径条数,否则,在(i,j)点累积的路径条数为(i-1,j)和(i,j-1)的路径条数之和。
我的代码:
//12ms过大集合
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int length_max=(int)obstacleGrid.size();
if(length_max==0)
return 0;
int length_min=(int)obstacleGrid[0].size();
if(length_min==0)
return 0;
vector<int> res_vec(length_min,0);
if(obstacleGrid[0][0]==1)
return 0;
res_vec[0]=1;
for(int i=1;i<length_min;i++)
if(res_vec[i-1]!=0&&obstacleGrid[0][i]==0)
res_vec[i]=1;
for(int i=1;i<length_max;i++){
if(res_vec[0]!=0&&obstacleGrid[i][0]==0)
res_vec[0]=1;
else
res_vec[0]=0;
for(int j=1;j<length_min;j++){
if(obstacleGrid[i][j]==1)
res_vec[j]=0;
else
res_vec[j]+=res_vec[j-1];
}
}
return res_vec[length_min-1];
}
};
小结如下:
(1) 上一题Unique Path1中使用了组合数学的方法来解答,其实不太适合本题,因为数学公式没法明确给出。上一题也尝试使用了递归的办法,提交超时,本题使用递归,依然提交超时,递归确实开销比较大了。
(2) 之前遇到过相似的迷宫问题,当时使用了堆栈或者队列来解决,所以这个问题我也尝试着使用队列去解决。发现,当输入的obstacleGrid矩阵比较小的时候,还不会超时,当输入的obstacleGrid矩阵较大(如20*30)时,就超时了。是否说明队列的办法不适合这个场景?队列的办法更适合找到一条合适的路径,而不是计算一共有多少合适的路径?
这是使用队列方法却超时的代码,不知道有没有什么更好的办法可以使得虽然使用队列但是却不超时呢?
//使用队列方法却超时的代码
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
if(obstacleGrid.size()==0)
return 0;
if(obstacleGrid[0].size()==0)
return 0;
int row_limit=(int)obstacleGrid.size()-1;
int col_limit=(int)obstacleGrid[0].size()-1;
GRID_NODE node1={0,0};
int path_count=0;
queue<GRID_NODE> que;
que.push(node1);
while(!que.empty()){
GRID_NODE tmp_node=que.front();
// std::cout<<"tmp_node.x="<<tmp_node.x<<"tmp_node.y="<<tmp_node.y<<std::endl;
que.pop();
if((tmp_node.x+1<=row_limit)&&(obstacleGrid[tmp_node.x+1][tmp_node.y]!=1))
que.push({tmp_node.x+1, tmp_node.y});
if((tmp_node.y+1<=col_limit)&&(obstacleGrid[tmp_node.x][tmp_node.y+1]!=1))
que.push({tmp_node.x, tmp_node.y+1});
if((tmp_node.x==row_limit)&&(tmp_node.y==col_limit))
path_count++;
}
return path_count;
}