0063. Unique Paths II (M)

Unique Paths II (M)

题目

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

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.

Note: m and n will be at most 100.

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

题意

在矩形中找到一条路径,起点为左上顶点,终点为右下顶点,路径中只能向右或向下走,且矩形中存在不能通过的障碍点,要求统计不同路径的个数。

思路

0062. Unique Paths (M) 方法一致,只是多了障碍点不好用组合数解决问题。使用动态规划,并用滚动数组进行优化。


代码实现

Java

动态规划

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[][] dp = new int[n][m];
        
        dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (i != 0 || j != 0) {
                    dp[i][j] = obstacleGrid[i][j] == 1 ? 0 : 
                    		((i == 0 ? 0 : dp[i - 1][j]) + (j == 0 ? 0 : dp[i][j - 1]));
                }
            }
        }
        
        return dp[n - 1][m - 1];
    }
}

滚动数组优化

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[] dp = new int[m];
        
        dp[0] = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                dp[j] = obstacleGrid[i][j] == 1 ? 0 : j > 0 ? dp[j - 1] + dp[j] : dp[j];
            }
        }
        
        return dp[m - 1];
    }
}

JavaScript

/**
 * @param {number[][]} obstacleGrid
 * @return {number}
 */
var uniquePathsWithObstacles = function (obstacleGrid) {
  let n = obstacleGrid.length
  let m = obstacleGrid[0].length
  let scroll = new Array(m).fill(0)
  scroll[0] = 1
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (obstacleGrid[i][j] === 1) {
        scroll[j] = 0
      } else {
        scroll[j] = j === 0 ? scroll[j] : scroll[j] + scroll[j - 1]
      }
    }
  }
  return scroll[m - 1]
}
posted @ 2020-07-14 01:35  墨云黑  阅读(148)  评论(0编辑  收藏  举报