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.
Note: m and n will be at most 100.
Example 1:
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
题意:
给定一个 M * N 的矩阵,其中1代表障碍物,0代表有路可走,规定每一步只能向右或者向下,求从左上角(0,0)到右下角(M-1,N-1)可走的路的数目。
分析:
用动态规划解(→_→递归应该会超时);
以f【i】【j】代表从(0,0)走到(i,j)时的路径数;首先判断(0,0)是不是障碍物,如果是则无路可走直接返回0,否则,f【0】【0】= 1;
由于第一行处于最上面,只能从左边往右走过来,如果该坐标有障碍物,从该坐标起到第一行末f【0】【j】都等于0,否则f【0】【j】= 1;由于第一列处于最左,只能从上往下走过来,如果该坐标有障碍物,从该坐标起到第一列末f【i】【0】都等于0,否则f【i】【0】= 1;对于其它位置,都有f【i】【j】= f【i】【j-1】+f【i-1】【j】;
结果返回f【M-1】【N-1】。
C++代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int x = obstacleGrid.size();
int y = obstacleGrid[0].size();
if(obstacleGrid[0][0])
return 0;
for(int j=0; j<y; j++)
if(!obstacleGrid[0][j])
obstacleGrid[0][j]=1;
else
{
for(;j<y;j++)
obstacleGrid[0][j]=0;
}
for(int i=1; i<x; i++)
if(!obstacleGrid[i][0])
obstacleGrid[i][0]=1;
else
{
for(;i<x;i++)
obstacleGrid[i][0]=0;
}
for(int i=1; i<x; i++)
for(int j=1; j<y; j++)
{
if(!obstacleGrid[i][j])
obstacleGrid[i][j]=obstacleGrid[i][j-1]+obstacleGrid[i-1][j];
else
obstacleGrid[i][j]=0;
}
return obstacleGrid[x-1][y-1];
}
};