我正在寻找最有效的算法,以便同时查找网络中连接的组件数和每个连接组件的节点数。
示例:
鉴于以下投入:
no_of_nodes = 8
graph_to = [1,1,3,5,6]
graph_from = [2,6,4,7,3]我将收到以下输出:
[[1, 2, 3, 4, 6], [5, 7], [8]]到目前为止,这就是我所拥有的:
def connections(no_of_nodes, graph_from, graph_to):
nodes = list(range(1, no_of_nodes+1))
singles = []
# removes all unconnected nodes
for node in nodes:
if node not in graph_from + graph_to:
singles.append([node])
conns = [[graph_from[0],graph_to[0]]]
graph_from.pop(0)
graph_to.pop(0)
n=0
k = 0
while n < len(graph_from):
x = graph_from[n]
y = graph_to[n]
if x in conns[k]:
conns[k].append(y)
graph_from.pop(n)
graph_to.pop(n)
else:
conns.append([x,y])
k += 1
print(conns)
n+=1
return conns + singles我已经找到了一种迭代节点的方法,假设所有连接都相邻地放置在graph_from列表中,但这当然不会适用于所有情况。
编辑:我正在寻找一种无需导入模块就可以完成此操作的方法。
发布于 2020-12-16 22:10:35
使用上面回答的总结过程,我能够制定下面的内容,在测试之后,它看起来是要检查的。
def connected(graph_nodes, graph_from, graph_to):
unseen = [i for i in range(1,graph_nodes + 1)]
edges = [[graph_from[i],graph_to[i]] for i in range(len(graph_from))]
connects = []
while unseen != []:
start = unseen[0]
connection = []
queue = [start]
unseen.remove(start)
while queue != []:
end = queue[-1]
if end not in connection:
connection.append(end)
queue = queue[:-1]
for k in edges:
if k[0] == end:
queue.append(k[1])
unseen.remove(k[1])
connects.append(connection)
return connects发布于 2020-12-16 21:09:35
使用网络
import networkx as nx
no_of_nodes = 8
graph_to = [1, 1, 3, 5, 6]
graph_from = [2, 6, 4, 7, 3]
g = nx.Graph(zip(graph_from, graph_to))
g.add_nodes_from(range(1, no_of_nodes + 1))
res = list(nx.connected_components(g))
print(res)输出
[{1, 2, 3, 4, 6}, {5, 7}, {8}]发布于 2020-12-16 22:12:33
基本的连通集算法是:
unseen中。unseen不是空的,则从其中删除一个随机元素,并将其放到队列中。如果unseen是空的,你就完了。- Remove the front element of the queue.
- Find all `unseen` elements that are connected to that front element. Remove them from `unseen` and add them to the queue.重复,直到队列为空。一旦队列为空,您已经从图中删除了一个连接组件。回到第二步。
编辑以改进格式。我想出了如何做双排巢
https://stackoverflow.com/questions/65331094
复制相似问题