簡體   English   中英

將字典中的鍵添加到列表中

[英]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)

Output:[16、12、21、17、28、20]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM