Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取可能路径的MxN网格(矩阵)问题_Python_Algorithm_Python 2.7 - Fatal编程技术网

Python 获取可能路径的MxN网格(矩阵)问题

Python 获取可能路径的MxN网格(矩阵)问题,python,algorithm,python-2.7,Python,Algorithm,Python 2.7,我有一个MxN矩阵(只填充了0和1,我必须“计算”所有可能的唯一路径。 考虑下面的例子: grid =[[1, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [1, 0, 1, 1], [1, 1, 1, 1]] 我正试图想出一个算法来解决这个问题,但我被难住了。有人知道一个算法可以解决这个问题吗?我需要为同样的问题编写一个python代码。我不需要代码。只需要算法 其他例子包括: grid =[[1, 0,

我有一个MxN矩阵(只填充了0和1,我必须“计算”所有可能的唯一路径。 考虑下面的例子:

grid =[[1, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 0],
       [1, 0, 1, 1],
       [1, 1, 1, 1]]
我正试图想出一个算法来解决这个问题,但我被难住了。有人知道一个算法可以解决这个问题吗?我需要为同样的问题编写一个python代码。我不需要代码。只需要算法

其他例子包括:

grid =[[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1]]
This has 5 paths. Each 1 in the diagonal form a path, since diagonal 1's cannot be part of path
这就是有效的答案:

def countIslands(rows, column, grid):
    def remove(i, j):
        if 0 <= i < rows and 0 <= j < column and grid[i][j] == 1:
            grid[i][j] = 0
            for x,y in zip([i+1, i-1, i, i], [j, j, j+1, j-1]):
                remove(x,y) 
            return 1
        return 0
    return sum(remove(i, j) for i in range(rows) for j in range(column))

grid = [[1,1,0,1],[0,0,1,0],[0,0,0,0],[1,0,1,1],[1,1,1,1]]
rows = 5
column = 4
final = countIslands(rows, column, grid)
print(final)
def countIslands(行、列、网格):
def移除(i,j):

如果0似乎希望获得连接组件的数量(usting 4-connectivity)

另请注意(由于您不需要标记组件,所以对当前问题的处理过度)

将网格视为:

  • 顶点是具有1的单元
  • 当两个顶点垂直或水平相邻时,它们之间有一条边
问题中的“路径”在图中表示a。因此,您必须计算这些组件。这可以通过算法完成


这里有一个讨论部分提供的解决方案。

帮助@gimme\u danger。我已经更新了原始问题中的答案
def countIslands(rows, column, grid):
    def remove(i, j):
        if 0 <= i < rows and 0 <= j < column and grid[i][j] == 1:
            grid[i][j] = 0
            for x,y in zip([i+1, i-1, i, i], [j, j, j+1, j-1]):
                remove(x,y) 
            return 1
        return 0
    return sum(remove(i, j) for i in range(rows) for j in range(column))

grid = [[1,1,0,1],[0,0,1,0],[0,0,0,0],[1,0,1,1],[1,1,1,1]]
rows = 5
column = 4
final = countIslands(rows, column, grid)
print(final)