【发布时间】:2016-03-08 05:02:36
【问题描述】:
我有一个代表 NxN 矩阵的一维 numpy 布尔数组(例如,一个 10x10 矩阵的值是 0 到 9,然后是 10 到 19,等等) 我的目标是找到相邻的“真实”元素的数量——上、下、左、右或对角线。
我解决这个问题的计划是遍历数组(对于 my_array 中的 x),当遇到“真”元素时,输入周围元素的搜索模式。如果周围元素之一也为真,则搜索其周围元素。但是,我不确定这是否是优化的搜索,并且递归地实现它被证明是困难的。
关于在 1D numpy 数组中搜索相邻元素的算法或方法有什么建议吗?
编辑:
因为我见过的深度优先搜索使用字典来设置元素之间的路径,所以我尝试创建一个函数来定义它(如下)。
我将其简化为只考虑左、右、上和下(还没有对角线),但边缘情况不起作用。
有了这个,我希望使用深度优先搜索功能,当找到“真实”元素时递归调用自身。
def getgraph(lst):
#print('here2')
for x in lst:
if x is 0:
graph[x] = set([x+1, x+n])
x = x+1
while (x > 0) and (x < (n-1)): #first row, excluding edges
graph[x] = set([(x-1),(x+1),(x+n)])
x= x+1
while x >= (n-1) and x < ((n-1)*n): #second to second last row, with edge cases
v = x%n
width = n-1
print('XN: %f' %v)
if (x % n) == 0:
graph[x] = set([x+1, x+n])
x = x+1
if (v) is width:
graph[x] = set([(x-1),(x+n)])
x = x+1
else:
graph[x] = set([(x-1), (x+1), (x+n), (x-n)])
x= x+1
while x >= (n-1)*n and x <= ((n*n)-1):
value = ((n*n)-1)
if x is value: # works with manually inputting last element number
graph[x] = set([(x-1),(x-n)])
x = x+1
else:
graph[x] = set([(x-1),(x+1),(x-n)])
x= x+1
print(graph)
return graph
【问题讨论】:
-
你做了什么?请至少添加一个 sn-p 代码。
-
欢迎来到 Stack Overflow!您的问题很难回答,因为它不包含您的代码。您需要发布您的代码,以便人们可以查看它并指出问题所在。最好创建一个Minimal, Complete, and Verifiable example。另见How do I ask a good question?。祝你好运!
-
听起来像是人生游戏。您可以在 Python 中寻找其他人的实现作为初学者,例如codereview.stackexchange.com/questions/40886/…。但通常最好先自己尝试,然后看看别人做了什么。
标签: python arrays algorithm numpy