def find_a_1():
for row_i, row in enumerate(matrix):
if '1' in row:
return {
'row': row_i,
'col': row.index('1'),
}
def walk_the_matrix(point):
""" Clear current point and move to adjacent cells that are "1s" """
# check if this is a valid cell to work on:
try:
if point['row'] < 0 or point['col'] < 0:
raise IndexError # prevent negative indexes
if matrix[point['row']][point['col']] == '0':
return # nothing to do here, terminate this recursion branch
except IndexError:
return # we're outside of the matrix, terminate this recursion branch
# clear this cell:
matrix[point['row']][point['col']] = '0'
# recurse to all 8 directions:
for i in (-1, 0, 1):
for j in (-1, 0, 1):
if (i, j) == (0, 0):
continue
walk_the_matrix({
'row': point['row'] + i,
'col': point['col'] + j,
});
import numpy as np
import scipy.signal as ss
kernel = np.ones((3,3))
count = ss.convolve2d(my_array, kernel, mode='same') # Count number of 1s around each cell
contig = my_array * count # Remove counts where the 'centre cell' is zero
一点递归就可以了。在
以下是对算法的描述:
1
0
1
单元格中,从第2点开始重复。在1
如果找到了,那么矩阵就不连通了为了澄清最后一点-如果矩阵中还有剩余的
1
,这意味着我们的算法没有到达它。由于它只移动到相邻的单元,所以我们得出结论,剩下的1
没有连接到步骤1中的初始1
。在代码如下:
示例:
^{pr2}$请注意,这会使
matrix
列表发生变异。在因为我误读了原始问题而编辑了
问题似乎可以归结为“有没有完全被0包围的1?”。在
计算每个细胞周围的细胞数的一个简单方法是使用2D卷积,假设{}由0和1组成
要检查
^{pr2}$my_array
是否有任何独立的1,只需检查contig
中是否有任何1:相关问题 更多 >
编程相关推荐