不同路徑 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)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章