leetcode Unique Paths II题解

题目描述:

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

中文理解:

给定一个二维矩阵,其中1代表障碍物,0代表通路,得出从矩阵左最上角到右最下角的所有路径数量。

解题思路:

设置path二维数组表示到i,j位置的路径数量,初始化时第一行和第一列,如果中间一个位置为1障碍物,则回来的路径数都为0,否则为1,同时如果该位置是障碍,仍然设置路径数为0,其他位置根据递推公式:path[i][j]=path[i-1][j]+path[i][j-1];。

代码(java):

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid.length==0)return 0;
        int[][] path=new int[obstacleGrid.length][obstacleGrid[0].length];
        boolean flag=true;
        for(int i=0;i

 

你可能感兴趣的:(leetcode)