如何修复此方法以返回节点在位置 i 与其他节点建立的所有连接

问题描述

给定一个有 2 个节点 (0,1) 的有向图:0 连接到 0 和 1。1 连接到 0。就像这个邻接矩阵:

Adj = [[1,1],# 1 represents connections and 0 no connection
       [1,0]]

我想要的输出如下:

v = [{0,1},{0}]  # Node 0 connects to itself and 1. Node 1 connects to node 0.

这意味着,位于 v[0] 的节点 0 连接到节点 0 和 1。位于 v[1] 的节点 1 仅连接到节点 0。所以,基本上它应该告诉与位置 i 的节点相连的节点

我做了什么:

>> import networkx as nx
>> import numpy as np
>> arr = np.array([[1,[1,0]])
>> G = nx.DiGraph()
>> G = nx.from_numpy_array(arr,create_using = nx.DiGraph)
>> L = []
>> for i in range (N): # N is the amount of nodes in the graph,in this case 2.
>>    aux = set(nx.edge_bfs(nx.Graph(G.edges),i))
>>    U.append(aux)
>> print(U)

Output: [{(0,1),(0,0)},{(1,0),0)}]

解决方法

我找到的解决方案是使用 nx.descendants 方法。

    for i in range (0,q):
      x = nx.descendants(G,i)

该代码段给出了从源节点可到达的所有节点,自循环除外。