gpt4 book ai didi

python - 在二维二进制矩阵中找到岛屿的数量

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:40:18 24 4
gpt4 key购买 nike

我正在尝试计算二维二进制矩阵中的岛(一组连接的 1 形成一个岛)的数量。

例子:

[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]
]

在上面的矩阵中有5个岛,分别是:

First: (0,0), (0,1), (1,1), (2,0)
Second: (1,4), (2,3), (2,4)
Third: (4,0)
Fourth: (4,2)
Fifth: (4,4)

为了计算 2D 矩阵中的岛屿数量,我将矩阵假设为图形,然后使用 DFS 类算法来计算岛屿数量。

我正在跟踪 DFS(递归函数)调用的次数,因为图表中会有那么多组件。

下面是我为此编写的代码:

# count the 1's in the island
def count_houses(mat, visited, i, j):
# base case
if i < 0 or i >= len(mat) or j < 0 or j >= len(mat[0]) or\
visited[i][j] is True or mat[i][j] == 0:
return 0
# marking visited at i, j
visited[i][j] = True
# cnt is initialized to 1 coz 1 is found
cnt = 1
# now go in all possible directions (i.e. form 8 branches)
# starting from the left upper corner of i,j and going down to right bottom
# corner of i,j
for r in xrange(i-1, i+2, 1):
for c in xrange(j-1, j+2, 1):
# print 'r:', r
# print 'c:', c
# don't call for i, j
if r != i and c != j:
cnt += count_houses(mat, visited, r, c)
return cnt


def island_count(mat):
houses = list()
clusters = 0
row = len(mat)
col = len(mat[0])
# initialize the visited matrix
visited = [[False for i in xrange(col)] for j in xrange(row)]
# run over matrix, search for 1 and then do dfs when found 1
for i in xrange(row):
for j in xrange(col):
# see if value at i, j is 1 in mat and val at i, j is False in
# visited
if mat[i][j] == 1 and visited[i][j] is False:
clusters += 1
h = count_houses(mat, visited, i, j)
houses.append(h)
print 'clusters:', clusters
return houses


if __name__ == '__main__':
mat = [
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]
]
houses = island_count(mat)
print houses
# print 'maximum houses:', max(houses)

我在参数中传递的矩阵输出错误。我得到 7 但有 5 簇。

我尝试调试任何逻辑错误的代码。但是我找不到问题出在哪里。

最佳答案

大锤做法,供引用

必须添加structure 参数np.ones((3,3)) 以添加对角连接

import numpy as np
from scipy import ndimage

ary = np.array([
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]
])

labeled_array, num_features = ndimage.label(ary, np.ones((3,3)))

labeled_array, num_features
Out[183]:
(array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 2],
[1, 0, 0, 2, 2],
[0, 0, 0, 0, 0],
[3, 0, 4, 0, 5]]), 5)

关于python - 在二维二进制矩阵中找到岛屿的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48758789/

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