通过递归遍历连接组件缺少一个节点[python]

时间:2017-11-07 19:59:08

标签: python graph-theory graph-traversal connected-components

尝试通过获取每个顶点,遍历它,然后跳到尚未分配给组件的下一个顶点来快速连接图形组件算法。

graph

这是图表。我目前得到的输出是:[1,1,1,1,1,0,3,3,3,3,4,4,4]

除了v​​1或v4都没有正确调用v5为其分配一个组外,其中显示了大部分正确的输出,因此它被识别为它自己的组。不知道为什么会这样。

adjacency_matrix = [[0,0,1,0,1,0,0,0,0,0,0,0,0],
                   [0,0,1,1,0,1,0,0,0,0,0,0,0],
                   [1,1,0,1,0,0,0,0,0,0,0,0,0],
                   [0,1,1,0,0,0,0,0,0,0,0,0,0],
                   [1,0,0,0,0,1,0,0,0,0,0,0,0],
                   [0,1,0,0,1,0,0,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,1,1,1,0,0,0],
                   [0,0,0,0,0,0,1,0,0,0,0,0,0],
                   [0,0,0,0,0,0,1,0,0,0,0,0,0],
                   [0,0,0,0,0,0,1,0,0,0,0,0,0],
                   [0,0,0,0,0,0,0,0,0,0,0,1,1],
                   [0,0,0,0,0,0,0,0,0,0,1,0,1],
                   [0,0,0,0,0,0,0,0,0,0,1,1,0]]

def Connected_Component(graph):
     # Number of vertices = Number of rows in matrix
     vertices = graph.__len__()
     # Array of zeroes to hold vertex component values
    components = [0] * vertices
    # Component groups start at 1, so 0 means unassigned
    current_component = 1

# Search all vertices connected
def traverse(vertex):
    # For each edge of this vertex
    for edge in range(0,vertex.__len__()):
        if vertex[edge] == 1:
            # Base case: If the vertex corresponding to the edge has already been visited & assigned a component
            if components[edge] > 0:
                print "Base case on " + str(edge) + " current component " + str(current_component)
                return
            # Otherwise, recursively search each connected vertex
            else:
                components[edge] = current_component
                print "recursively traversing " + str(edge)+ " current component " + str(current_component)
                traverse(graph[edge])

for vertex in range(0,vertices):
    # If the component of the current vertex has already been assigned, skip this iteration
    if components[vertex] > 0:
        print "skipping " + str(vertex)
        continue
    else:
        # Traverse this vertex
        print "traversing " + str(vertex)+ " current component " + str(current_component)
        traverse(graph[vertex])
        current_component += 1

return components

print Connected_Component(adjacency_matrix)

0 个答案:

没有答案