Unique Paths II

Important point:
During the iniitialize, the top or left side, if one grid is BLOCK, the rest of those points are all blocked. 

public class Solution {
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */
    private static final int BLOCK = 1;
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // write your code here
        if (obstacleGrid == null || obstacleGrid.length == 0) {
            return 0;
        }
        
        if (obstacleGrid[0] == null || obstacleGrid[0].length == 0) {
            return 0;
        }
        
        int nRow = obstacleGrid.length;
        int nCol = obstacleGrid[0].length;
        
        if (obstacleGrid[0][0] == BLOCK) {
            return 0;
        }
        int[][] f = new int[nRow][nCol];
        f[0][0] = 1;
        //initialization
        //f[x][y]: unique path number from (0,0) to (x,y)
        for (int i = 1; i < nCol; i++) {
            if (obstacleGrid[0][i] == BLOCK || f[0][i - 1] == 0) {
                f[0][i] = 0;
            } else {
                f[0][i] = 1;
            }
        }
        
        for (int i = 1; i < nRow; i++) {
            if (obstacleGrid[i][0] == BLOCK || f[i - 1][0] == 0) {
                f[i][0] = 0;
            } else {
                f[i][0] = 1;
            }
        }
        
        for (int i = 1; i < nRow; i++) {
            for (int j = 1; j < nCol; j++) {
                if (obstacleGrid[i][j] == BLOCK) {
                    f[i][j] = 0;
                } else {
                    f[i][j] = f[i - 1][j] + f[i][j - 1]; 
                }
            }
        }
        
        return f[nRow - 1][nCol - 1];
    }
}

 

posted on 2017-05-25 07:13  codingEskimo  阅读(90)  评论(0编辑  收藏  举报

导航