在给定距离BFS算法中获取邻居

时间:2018-11-03 21:45:09

标签: python breadth-first-search graph-traversal

我必须编写一个函数,该函数将返回一个set,其中包含给定距离内源顶点的邻居。例如示例图:

        {0: [1, 3],
         1: [2],
         2: [],
         3: [4],
         4: [1, 5],
         5: [],
         6: [1]}

通过将此图形传递给函数+源顶点为0且传递距离= 2,结果应为:{1,2,3,4}

我该如何实现?

1 个答案:

答案 0 :(得分:0)

我不熟悉图论,但以下内容似乎得到了正确的结果。距离为2:

{1, 2, 3, 4}

import networkx as nx

def main():
    distance = 2
    source_node = 0

    dict1 = {0: [1, 3],
             1: [2],
             2: [],
             3: [4],
             4: [1, 5],
             5: [],
             6: [1]}

    g = nx.DiGraph()

    # fill graph
    for node, list1 in dict1.items():
        for n in list1:
            g.add_edge(node, n)

    neighbors = []
    M = [source_node]

    for _ in range(distance):
        M = find_neigbors(g,M)
        neighbors.extend(M)

    print(neighbors)

def find_neigbors(g, vertices):
    p = []
    for node in vertices:
        p.extend(g.adj[node])
    return p

main()

更新:Wikipedia具有实现BFS算法的Python函数here

更新:另请参见BFS algorithm in Python