gpt4 book ai didi

python - 如何找到连通分量?

转载 作者:太空狗 更新时间:2023-10-29 20:39:02 25 4
gpt4 key购买 nike

我正在为类 Graph 编写函数 get_connected_components:

def get_connected_components(self):
path=[]
for i in self.graph.keys():
q=self.graph[i]
while q:
print(q)
v=q.pop(0)
if not v in path:
path=path+[v]
return path

我的图表是:

{0: [(0, 1), (0, 2), (0, 3)], 1: [], 2: [(2, 1)], 3: [(3, 4), (3, 5)], \
4: [(4, 3), (4, 5)], 5: [(5, 3), (5, 4), (5, 7)], 6: [(6, 8)], 7: [], \
8: [(8, 9)], 9: []}

其中键是节点,值是边。我的函数给了我这个连接的组件:

[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), \
(5, 4), (5, 7), (6, 8), (8, 9)]

但我会有两个不同的连接组件,例如:

[[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), \
(5, 3), (5, 4), (5, 7)],[(6, 8), (8, 9)]]

我不明白我在哪里犯了错误。谁能帮帮我?

最佳答案

我喜欢这个算法:

def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)

不仅短小精悍,而且速度很快。像这样使用它(Python 2.7):

old_graph = {
0: [(0, 1), (0, 2), (0, 3)],
1: [],
2: [(2, 1)],
3: [(3, 4), (3, 5)],
4: [(4, 3), (4, 5)],
5: [(5, 3), (5, 4), (5, 7)],
6: [(6, 8)],
7: [],
8: [(8, 9)],
9: []}

edges = {v for k, vs in old_graph.items() for v in vs}
graph = defaultdict(set)

for v1, v2 in edges:
graph[v1].add(v2)
graph[v2].add(v1)

components = []
for component in connected_components(graph):
c = set(component)
components.append([edge for edges in old_graph.values()
for edge in edges
if c.intersection(edge)])

print(components)

结果是:

[[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), (5, 4), (5, 7)],
[(6, 8), (8, 9)]]

谢谢阿帕帕拉发现了这个错误。

关于python - 如何找到连通分量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10301000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com