image.png

解题思路

动态规划

image.png

  1. public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  2. int R = obstacleGrid.length;
  3. int C = obstacleGrid[0].length;
  4. //特判
  5. if (obstacleGrid[0][0] == 1)
  6. return 0;
  7. obstacleGrid[0][0] = 1;
  8. //对第一列进行判断
  9. for (int i = 1;i < R;i++){
  10. obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i-1][0] == 1) ?1:0;
  11. }
  12. //对第一行进行判断
  13. for(int j = 1;j < C;j++){
  14. obstacleGrid[0][j] = (obstacleGrid[0][j] == 0 && obstacleGrid[0][j-1] == 1) ? 1:0;
  15. }
  16. for (int i = 1;i < R;i++){
  17. for (int j = 1;j < C;j++){
  18. if (obstacleGrid[i][j] == 0)
  19. obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
  20. else
  21. obstacleGrid[i][j] = 0;
  22. }
  23. }
  24. return obstacleGrid[R-1][C-1];
  25. }