python连通区域计算长度_Python中图的连通分量计数算法

我试图编写一个脚本,计算一个图的连接组件,但我无法得到正确的解决方案。

我有一个有6个节点(顶点)的简单图,节点1和2是连接的,节点3和4是连接的(6个顶点;1-2,3-4,5,6)。所以这个图包含4个连接的组件。我使用下面的脚本计算连接的组件,但得到的结果是错误的(2)。nodes = [[1, [2], False], [2, [1], False], [3, [4], False], [4, [3], False], [5, [], False], [6, [], False]]

# 6 nodes, every node has an id, list of connected nodes and boolean whether the node has already been visited

componentsCount = 0

def mark_nodes( list_of_nodes):

global componentsCount

componentsCount = 0

for node in list_of_nodes:

node[2] = False

mark_node_auxiliary( node)

def mark_node_auxiliary( node):

global componentsCount

if not node[2] == True:

node[2] = True

for neighbor in node[1]:

nodes[neighbor - 1][2] = True

mark_node_auxiliary( nodes[neighbor - 1])

else:

unmarkedNodes = []

for neighbor in node[1]:

if not nodes[neighbor - 1][2] == True: # This condition is never met. WHY???

unmarkedNodes.append( neighbor)

componentsCount += 1

for unmarkedNode in unmarkedNodes:

mark_node_auxiliary( nodes[unmarkedNode - 1])

def get_connected_components_number( graph):

result = componentsCount

mark_nodes( graph)

for node in nodes:

if len( node[1]) == 0: # For every vertex without neighbor...

result += 1 # ... increment number of connected components by 1.

return result

print get_connected_components_number( nodes)

有人能帮我找出错误吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值