LeetCode 63. 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:

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

Reference Answer

思路分析

典型的回溯法应用:

  1. 首先初始与输入矩阵相同维度的result矩阵,result[i][j]保存了从左上角到达输入矩阵input[i][j]的路径数;
  2. 设定边界条件,不难知道,依据路径定义,当row = 0 or column = 0 对应的result,除非出现障碍点,矩阵结果均为1(对应到达该点只有一条路径);针对result矩阵,对应row = 0 and column != 0 及 row != 0 and column ==0 时出现障碍点后面均为不可达,即为0;可通过遍历result矩阵边界时,在出现障碍点之后直接跳出赋值循环实现,详细见代码;
  3. 对result矩阵,当row != 0 and column != 0 时,其对应矩阵result[i][j] = result[i-1][j] + result[i][j-1],这个规律可自己画几个例子观察一下总结得到。
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        row_len, col_len = len(obstacleGrid), len(obstacleGrid[0])
        res = [[0 for i in range(col_len)] for j in range(row_len)]
        
        for i in range(row_len):
            if obstacleGrid[i][0] == 0:
                res[i][0] = 1
            else:
                res[i][0] = 0
                break    # 跳出循环,这样后面就全为0,解决边界问题
        for i in range(col_len):
            if obstacleGrid[0][i] == 0:
                res[0][i] = 1
            else:
                res[0][i] = 0
                break    # 跳出循环,这样后面就全为0,解决边界问题
        for i in range(1, row_len):
            for j in range(1, col_len):
                if obstacleGrid[i][j] == 1:
                    res[i][j] = 0
                else:
                    res[i][j] = res[i-1][j] + res[i][j-1]
        return res[row_len-1][col_len-1]
 

反思:

  1. 首先,要注意python二维矩阵的创建:res = [[0 for i in range(col_len)] for j in range(row_len)],列矩阵在里面,行矩阵在外面;这点要切记,自己花了很长时间才找到问题;
  2. 注意获取二维矩阵行列的方式:row_len, col_len = len(obstacleGrid), len(obstacleGrid[0])
  3. 注意动态循环实现的方式,采用了回溯法,从前向后实现,避开了递归,将算法复杂度大大减轻。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/83019991