一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
网格中的障碍物和空位置分别用 1
和 0
来表示。
说明:m 和 n 的值均不超过 100。
示例 1:
输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2
条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
class Solution {
public:
/*
f(x,y)=1 {x==m&&y==n}
f(x,y)=f(x+1,y) {y==n}
f(x,y)=f(x,y+1) {x==m}
f(x,y)=f(x+1,y)+f(x,y+1)
*/
int m,n;
int dp(vector<vector<int>> &obs, vector<vector<int>> &help, int x, int y){
if(help[x][y]!=-1)
return help[x][y];
if(obs[x][y])
return help[x][y] = 0;
if(x==m && y==n)
return help[x][y] = 1;
if(x==m)
return help[x][y] = dp(obs,help,x,y+1);
if(y==n)
return help[x][y] = dp(obs,help,x+1,y);
return help[x][y] = dp(obs,help,x+1,y) + dp(obs,help,x,y+1);
}
int uniquePathsWithObstacles(vector<vector<int>>& obs) {
m = obs.size()-1;
n = obs[0].size()-1;
vector<vector<int>> help(m+1,vector<int>(n+1,-1));
return dp(obs,help,0,0);
}
};
class Solution:
def dp(self,obs,help,x,y,m,n):
if help[x][y]!=-1:
return help[x][y]
if obs[x][y]:
help[x][y] = 0
elif x==m and y==n:
help[x][y] = 1
elif x==m:
help[x][y] = self.dp(obs,help,x,y+1,m,n)
elif y==n:
help[x][y] = self.dp(obs,help,x+1,y,m,n)
else:
help[x][y] = self.dp(obs,help,x+1,y,m,n) + self.dp(obs,help,x,y+1,m,n)
return help[x][y]
def uniquePathsWithObstacles(self, obs):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m,n = len(obs), len(obs[0])
help = [[-1 for _ in range(0,n)] for _ in range(0,m)]
return self.dp(obs,help,0,0,m-1,n-1)