[英]Finding adjacent elements in 1D numpy array
我有一個表示NxN矩陣的一維numpy布爾數組(例如,一個10x10矩陣的值是0到9,然后是10到19,依此類推。)我的目標是找出相鄰的“ true”元素的數量-上,下,左,右或對角線。
我解決這個問題的計划是遍歷數組(對於my_array中的x),當遇到'true'元素時,為周圍的元素輸入搜索模式。 如果周圍元素之一也為真,那么它將搜索其周圍元素。 但是,我不確定這是否是優化的搜索,並且以遞歸方式實現它非常困難。
關於在1D numpy數組中搜索相鄰元素的算法或方法有何建議?
編輯:
因為我看到的深度優先搜索使用字典來設置元素之間的路徑,所以我嘗試創建一個函數來定義此內容(如下)。
我將其簡化為僅考慮左,右,上方和下方(尚無對角線),但是邊緣情況不起作用。
有了這個,我希望使用深度優先搜索功能,在找到“ true”元素時遞歸調用自身。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.