1. 题目2. 思路
(1) 动态规划 3. 代码
1. 题目
若网格[i,j]处有障碍,则到达网格[i,j]的路径数为0,否则,到达网格[i,j]的路径数为f(i,j)=f(i-1,j)+f(i,j-1)。初始化时,对于最左边和最上面的网格,若到达前一个网格的路径数为0,则之后网格的路径数均为0。 3. 代码
public class Test { public static void main(String[] args) { } } class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid[0][0] == 1) { return 0; } int m = obstacleGrid.length; int n = obstacleGrid[0].length; int[][] dp = new int[m][n]; dp[0][0] = 1; for (int i = 1; i < m; i++) { if (dp[i - 1][0] == 0 || obstacleGrid[i][0] == 1) { dp[i][0] = 0; } else { dp[i][0] = 1; } } for (int i = 1; i < n; i++) { if (dp[0][i - 1] == 0 || obstacleGrid[0][i] == 1) { dp[0][i] = 0; } else { dp[0][i] = 1; } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (obstacleGrid[i][j] == 1) { dp[i][j] = 0; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)