将字典中的键添加到列表中

Add keys from dictionary to a list

我的代码需要一些帮助。遍历 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)

我修改了bfs方法,见下文。更新后的代码基本上是逐层遍历图形,使用双端队列为 FIFO 提供更高的效率。

from collections import deque
def bfs(graph, start):
    deq = deque([start])
    visited = [start]
    while deq:
        for _ in range(len(deq)):
            node = deq.popleft()
            for neighbour in graph[node]:
                if neighbour not in visited:
                    visited.append(neighbour)
                    deq.append(neighbour)
    print(visited)

输出:[16、12、21、17、28、20]