[LeetCode] 63. Unique Paths II

這題就是Unique Paths的變種,區(qū)別在于增加了一些邊界條件:

  • 如果(x, y)有障礙,由于不可達(dá),f(x, y) = 0。

  • 如果(0, 0)有障礙,f(row - 1, column - 1) = 0

  • 如果第0行上有障礙,由于機(jī)器人只能向下或向右走,障礙右側(cè)的格子均不可達(dá)

  • 如果第0列上有障礙,由于機(jī)器人只能向下或向右走,障礙下側(cè)的格子均不可達(dá)

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid[0][0] == 1) {
            return 0;
        }
        int row = obstacleGrid.length;
        int column = obstacleGrid[0].length;
        int[][] f = new int[row][column];
        f[0][0] = 1;

        // 1. find the start of invalid row index
        int startOfInvalidRowIndex = row;
        for (int i = 0; i < row; i++) {
            if (obstacleGrid[i][0] == 1 && i < startOfInvalidRowIndex) {
                startOfInvalidRowIndex = i;
            }
            if (i >= startOfInvalidRowIndex) {
                f[i][0] = 0;
            } else {
                f[i][0] = 1;
            }
        }

        // 2. find the start of invalid column index
        int startOfInvalidColumnIndex = column;
        for (int j = 0; j < column; j++) {
            if (obstacleGrid[0][j] == 1 && j < startOfInvalidColumnIndex) {
                startOfInvalidColumnIndex = j;
            }
            if (j >= startOfInvalidColumnIndex) {
                f[0][j] = 0;
            } else {
                f[0][j] = 1;
            }
        }

        // 3. calculate f (set the value of invalid grids to 0)
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < column; j++) {
                if (obstacleGrid[i][j] == 1) {
                    f[i][j] = 0;
                } else {
                    f[i][j] = f[i - 1][j] + f[i][j - 1];
                }
            }
        }

        return f[row - 1][column - 1];
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容