【发布时间】:2020-05-24 18:34:31
【问题描述】:
我需要一些关于我的代码的帮助。遍历 numpy 数组后,我得到一个字典,您可以在其中查看哪个元素与谁连接。 BFS 方法将其整理并放入访问列表中。我需要弄清楚如何将密钥放入队列中。有一个起始元素。但不是所有的键,只是相互连接的键。如您所见,数组中有两个区域的图形。
import numpy as np
def graph():
a = np.array([
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 16, 12, 21, 0, 0, 0, 0],
[0, 16, 0, 0, 17, 20, 0, 0, 0],
[0, 12, 0, 0, 28, 0, 31, 0, 0],
[0, 21, 17, 28, 0, 18, 19, 23, 0],
[0, 0, 20, 0, 18, 0, 0, 11, 0],
[0, 0, 0, 31, 19, 0, 0, 27, 0],
[0, 0, 0, 0, 23, 11, 27, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]],
)
graph = {}
for r in range(len(a)):
for c in range(len(a)
if a[r, c] > 0:
d = [r-1, c+1, r+1, c-1]
if a[d[0], c] > 0 or a[r, d[1]] or a[d[2], c] or a[r, d[3]]:
graph[a[r, c]] = []
if a[d[0], c] > 0:
graph[a[r, c]].append(a[d[0], c])
if a[r, d[1]] > 0:
graph[a[r, c]].append(a[r, d[1]])
if a[d[2], c] > 0:
graph[a[r, c]].append(a[d[2], c])
if a[r, d[3]] > 0:
graph[a[r, c]].append(a[r, d[3]])
return(graph)
def bfs(图形,开始):
queue = [start]
visited = [start]
while queue:
for neighbour in graph.keys():
if neighbour in queue:
visited.append(graph[neighbour])
queue.pop(0)
result = 0
print(queue)
print(visited)
bfs(graph(), 16)
【问题讨论】:
-
对于元素的迭代访问,使用列表列表将比使用数组更有效。
标签: python numpy dictionary breadth-first-search