gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:34:10 27 4
gpt4 key购买 nike

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

grid =[[1, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[1, 0, 1, 1],
[1, 1, 1, 1]]
The rules of the solution are:
1) A path can be of length 1
2) A path should contains only 1's
3) Diagonal 1's are not part of a path, they stand alone as 1 path. They can be part of a path if they have adjacent 1's. for Eg:

grid_example =[[1, 0],
[0, 1]] - This grid has 2 paths, first row 1 is one path and second-row 1 is the other path


With the above rules, the initial grid has 3 path
a) The two 1's in row 1
b) The single 1 in row 2
c) The series of seven 1's in row 4 and 5

我正在尝试思考如何解决这个问题的算法,但我被难住了。有人知道可以解决这个问题的算法吗?我需要为此编写一个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)

最佳答案

将您的网格视为 undirected graph :

  • 顶点是带有 1 的单元格;
  • 两个顶点之间有一条,前提是这些顶点垂直或水平相邻

问题中的“路径”意味着 connected component用图表术语来说。所以你必须计算这些组件。这可以通过 Depth-first search 来完成算法。

这是一个等效的 leetcode problem在讨论部分提供解决方案。

关于python - 获取可能路径的 MxN 网格(矩阵)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60185585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com