一个机器人位于一个 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. 向下 -> 向下 -> 向右 -> 向右
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-paths-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的超时代码:
public class Main {
public static void main(String[] args) {
// int a[][] = {{0,0,0},{0,1,0},{0,0,0}};
int a[][] = {{1,0}};
System.out.println(uniquePathsWithObstacles(a));
}
public static int ans = 0;
public static int dx[] = {0, 1};
public static int dy[] = {1};
public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid[0][0] == 1) {
return 0;
}
dfs(obstacleGrid, 0, 0);
return ans;
}
private static void dfs(int[][] obj, int x, int y) {
if (x == obj.length-1 && y == obj[0].length-1) {
ans++;
return;
}
for (int i=0; i<2; i++) {
int tmpx = x + dx[i];
int tmpy = y + dy[i];
if (tmpx < obj.length && tmpy < obj[0].length && obj[tmpx][tmpy] != 1) {
dfs(obj, tmpx, tmpy);
}
}
return;
}
}
大佬的AC代码:dfs+记忆化
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int row = obstacleGrid.length;
int col = obstacleGrid[0].length;
int[][] mem = new int[row][col];
for (int i = 0; i < row; i++) {
Arrays.fill(mem[i],-1);
}
return dfsUniquePathsWithObstacles(obstacleGrid,0,0,mem);
}
private int dfsUniquePathsWithObstacles(int[][] board, int i, int j,int[][] mem) {
if (i == board.length - 1 && j == board[0].length - 1 && board[i][j] == 0) {
return 1;
}
if (i >= board.length || j >= board[0].length || board[i][j] == 1) {
return 0;
}
if (mem[i][j] != -1) {
return mem[i][j];
}
int total = 0;
total += dfsUniquePathsWithObstacles(board, i + 1, j, mem);
total += dfsUniquePathsWithObstacles(board, i, j + 1, mem);
mem[i][j] = total;
return total;
}
作者:pdzz
链接:https://leetcode-cn.com/problems/unique-paths-ii/solution/java-dpdfs-ji-yi-hua-chao-yue-100-by-pdzz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。