Я пытаюсь написать скрипт, который подсчитывает связанные компоненты графа, и не могу найти правильное решение. У меня есть простой граф с 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)
Может ли кто-нибудь помочь мне найти ошибку?
get_connected_components_number(graph)
может показаться, что вы помечаете все узлы как посещенные, а затем подсчитываете количество узлов без соединений (очевидно, 2). Честно говоря, я не знаю, что вы пытаетесь сделать с помощью этой программы. - person dln385   schedule 23.10.2010