Unique Paths II
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]; } }
以上是关于Unique Paths II的主要内容,如果未能解决你的问题,请参考以下文章