惟一路徑問題II

原題

  Follow up for 「Unique Paths」:
  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.
  For example,
  There is one obstacle in the middle of a 3x3 grid as illustrated below.算法

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

  The total number of unique paths is 2.
  Note: m and n will be at most 100.數組

題目大意

  惟一路徑問題後續,若是路徑中有障礙,求總的路徑的種數。【惟一路徑問題】
  注意:網格的行數和列數都不超過100ide

解題思路

  採用分治求解方法
  用一個m*n的組數A保存結果。
  對於A數組中的元素有。
  一、當x=0或者y=0時,而且(x, y)位置無障礙。有A[x][y] = 1; 有障礙就是0
  二、當x>=1而且y>=1時,而且(x, y)位置無障礙。有A[x][y] = A[x-1][y]+A[x][y-1]。 有障礙就是0
  三、所求的結點就是A[m-1][n-1]。spa

代碼實現

算法實現類.net

public class Solution {

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // 輸入校驗
        if (obstacleGrid == null || obstacleGrid.length < 1 || obstacleGrid[0].length < 1
                || obstacleGrid[0][0] == 1
                || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) {
            return 0;
        }

        int rows = obstacleGrid.length;
        int cols = obstacleGrid[0].length;
        int[][] result = new int[rows][cols];

        // 第一個位置有多少種方法,無障礙就是1種,有障礙就是0種
        result[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0;

        for (int i = 1; i < cols; i++) {
            result[0][i] = obstacleGrid[0][i] == 0 ? result[0][i - 1] : 0;
        }

        for (int i = 1; i < rows; i++) {
            result[i][0] = obstacleGrid[i][0] == 0 ? result[i - 1][0] : 0;
        }

        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                result[i][j] = obstacleGrid[i][j] == 0 ? result[i - 1][j] + result[i][j - 1] : 0;
            }
        }

        return result[rows - 1][cols - 1];
    }


    // 使用遞歸方法會超時
    public int uniquePathsWithObstacles2(int[][] obstacleGrid) {
        // 輸入校驗
        if (obstacleGrid == null || obstacleGrid.length < 1 || obstacleGrid[0].length < 1
                || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) {
            return 0;
        }
        int[] result = {0};
        solve(obstacleGrid, 0, 0, result);
        return result[0];
    }

    public void solve(int[][] grid, int row, int col, int[] sum) {
        // 到達終點
        if (row == grid.length - 1 && col == grid[0].length - 1) {
            sum[0]++;
        }
        // 沒有到終點,點在棋盤內,而且當前位置不是
        else if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 0) {
            // 往右走
            solve(grid, row, col + 1, sum);
            // 往下走
            solve(grid, row + 1, col, sum);
        }
    }
}
相關文章
相關標籤/搜索