在迷宫中寻找障碍物的路径数

时间:2019-03-03 21:13:52

标签: python algorithm

我一直在研究this leetcode问题,该问题实际上是在给定obstacleGrid矩阵的情况下找到迷宫中有效路径的数量。如果obstacleGrid[i][j] == 1,则我们在(i,j)处有一个障碍,否则我们有零,这是一个有效点。我们只能以从左上方到右下方为目标上下移动。

我写了下面的代码:

def uniquePathsWithObstacles(self, obstacleGrid):
    # obstruction at the start
    if (obstacleGrid[0][0] == 1): return 0
    # obstruction at the end
    if (obstacleGrid[-1][-1] == 1): return 0
    m, n = len(obstacleGrid), len(obstacleGrid[0])
    memo = [[0] * n] * m
    # starting move
    memo[0][0] = 1
    # now check the first row
    for j in range(1, n):
        memo[0][j] = 1 if (obstacleGrid[0][j] == 0 and memo[0][j-1] != 0) else 0
    # now check the first column
    for i in range(1, m):
        memo[i][0] = 1 if (obstacleGrid[i][0] == 0 and memo[i-1][0] != 0) else 0
    # now check everything else
    for i in range(1, m):
        for j in range(1, n):
            if (obstacleGrid[i][j] == 1): memo[i][j] = 0
            else: memo[i][j] = memo[i-1][j] + memo[i][j-1]
    return memo[-1][-1]

我采用了明显的DP方法,我知道这个想法可行,但是代码出了点问题。由于某些原因,我认为我的memo矩阵无法正确更新?我觉得问题出在我的脸上,但由于某种原因我看不到它。任何帮助表示赞赏!

编辑:对于obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]],如果我在return语句之前有一个print(memo),则得到[[1, 1, 2], [1, 1, 2], [1, 1, 2]]。碰巧这给了我正确的答案,但是memo矩阵是错误的!

3 个答案:

答案 0 :(得分:0)

一个问题出在memo = [[0] * n] * m行中。 这实际上并不会创建相同列表的m个副本,而是只会创建一次[0] * n列表,然后创建memo作为对此列表的m引用列表清单。因此,对这些列表进行的任何更改都会修改所有其他列表!

您可以自己尝试:

memo = [[0] * 3] * 4
memo[0][1] = 1
print(memo)

这给出了[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]

相反,您必须自行初始化每个列表,例如

memo = []
for i in range(m):
  memo.append([0] * n)

答案 1 :(得分:0)

我只是尝试将递归作为比较而不是答案。

import numpy as np

def number_of_paths(obstacles):
    """
    Calculate the number of paths available in a maze with obstacles, with only right and down moves, from top left
    to bottom right.

    Args:
        obstacles (ndarray): binary matrix with 1 representing obstacle

    Returns:
         int: the number of paths
    """
    if obstacles[0,0] == 1:
        raise ValueError  # cannot start on an obstacle
    count = 0
    if obstacles.shape == (2,1):
        return 1
    if obstacles.shape == (1,2):
        return 1
    if obstacles.shape[1] > 1 and obstacles[0,1] == 0:
        count += number_of_paths(obstacles[:,1:])
    if obstacles.shape[0] > 1 and obstacles[1,0] == 0:
        count += number_of_paths(obstacles[1:,:])
    return count

答案 2 :(得分:0)

您的代码正确,并且必须根据以下内容更新1行:

<script src="https://unpkg.com/video.js@6.1.0/dist/video.js"></script>
<script src="javascripts/silvermine-videojs-chromecast.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"></script>