微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何修复此方法以返回节点在位置 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)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。