Networkx:遍历遍历图

时间:2019-05-01 16:59:33

标签: python graph networkx breadth-first-search

假设我在networkx中有以下图形

import networkx as nx

g = nx.Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(3, 1)
g.add_edge(4, 2)

所以基本上是3-1-0-2-4行。

是否有networkx种通过“波动”执行BFS搜索的方法?像这样:

for x in nx.awesome_bfs_by_waves_from_networkx(g, 0):
    print(x)
# should print
# [1, 2]
# [3, 4]

换句话说,我想找到所有1环邻居,然后是2环,等等。

我可以通过使用Queue来做到这一点,但是我想尽可能使用networkx工具。也可以使用具有不同depth_limit值的多个迭代器,但我希望有可能找到更漂亮的方法。

UPD:对于我来说,有一个懒惰的解决方案,它不需要遍历整个图,这很重要,因为我的图可能很大,如果需要,我希望能够尽早停止遍历。

2 个答案:

答案 0 :(得分:1)

您可以使用Dijkstra算法从0(或任何其他节点n)计算最短路径,然后按距离对节点进行分组:

from itertools import groupby
n = 0
distances = nx.shortest_paths.single_source_dijkstra(g, n)[0]
{node: [node1 for (node1, d) in y] for node,y 
                                   in groupby(distances.items(), 
                                              key=lambda x: x[1])}
#{0: [0], 1: [1, 2], 2: [3, 4]}

如果您要按环前进(也称为地壳),请使用邻域的概念:

core = set()
crust = {n} # The most inner ring
while crust:
    core |= crust
    # The next ring
    crust = set.union(*(set(g.neighbors(i)) for i in crust)) - core

答案 1 :(得分:1)

函数nx.single_source_shortest_path_length(G, source=0, cutoff=7)应该提供您需要的信息。但是它返回一个由节点指定距离源的距离的字典。因此,您必须对其进行处理才能将其按距离分组。这样的事情应该起作用:

from itertools import groupby
spl = nx.single_source_shortest_path_length(G, source=0, cutoff=7)
rings = [set(nodes) for dist, nodes in groupby(spl, lambda x: spl[x])]
相关问题