简体   繁体   English

Networkx:通过波遍历图

[英]Networkx: Traverse graph by waves

Suppose i have a following graph in networkx 假设我在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)

So it's basically 3-1-0-2-4 line. 所以基本上是3-1-0-2-4行。

Is there are a networkx way to perform BFS search by "waves"? 是否有networkx方式可以通过“ waves”执行BFS搜索? Something like this: 像这样:

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

In other words i want to find all 1-ring neighborhood, then 2-ring, etc. 换句话说,我想找到所有1环邻域,然后是2环,依此类推。

I'm able to do this by using Queue, but i interested in using networkx tools if it possible. 我可以通过使用Queue来做到这一点,但是我对使用networkx工具(如果可能)感兴趣。 Also it's possible to use multiple iterators with different depth_limit values, but i hope that it's possible to find more beautiful way. 也可以使用具有不同depth_limit值的多个迭代器,但我希望有可能找到更漂亮的方法。

UPD: It's important for me to have a lazy solution which will not require to traverse whole graph, because my graph can be quite big and i want to be able to stop traversing early if it needed. UPD:对于我来说,拥有一个不需要遍历整个图的惰性解决方案很重要,因为我的图可能很大,并且我希望能够在需要时尽早停止遍历。

You can calculate shortest paths from 0 (or any other node n ) using Dijkstra algorithm and then group the nodes by distance: 您可以使用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]}

If you want to proceed by rings (also known as crusts ), use the concept of the neighborhood: 如果要按环(也称为外壳 )进行操作,请使用邻域的概念:

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

The function nx.single_source_shortest_path_length(G, source=0, cutoff=7) should provide the information you need. 函数nx.single_source_shortest_path_length(G, source=0, cutoff=7)应该提供所需的信息。 But it returns a dict keyed by node to distance from source. 但是它返回一个由节点指定距离源的距离的字典。 So you have to process it to get it into groups by distance. 因此,您必须对其进行处理才能将其按距离分组。 Something like this should work: 这样的事情应该起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM