【Leetcode】Unique Paths II (DP)

来源:互联网 发布:急难先锋8016优化 编辑:程序博客网 时间:2024/06/05 07:20

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]]

The total number of unique paths is 2.

Note: m and n will be at most 100.

这道题和I差不多,只是在初始化的时候一旦遇到了1,后面的都要变成0

如果obs(i,j)=1 f(i,j)=0

递推式还是

f(i,j)=f(i-1,j)+f(i,j-1)

public int uniquePathsWithObstacles(int[][] obstacleGrid) {int row = obstacleGrid.length;int col = obstacleGrid[0].length;int[][] result = new int[row][col];for (int i = 0; i < row; i++) {if (obstacleGrid[i][0] != 1)result[i][0] = 1;elsebreak;}for (int i = 0; i < col; i++) {if (obstacleGrid[0][i] != 1)result[0][i] = 1;elsebreak;}for (int i = 1; i < row; i++) {for (int j = 1; j < col; j++) {if (obstacleGrid[i][j] != 1)result[i][j] = result[i - 1][j] + result[i][j - 1];}}return result[row - 1][col - 1];}


0 0
原创粉丝点击