不同路径 II(dfs+记忆化)

 一个机器人位于一个 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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值