Trying to do a very quick connected components algorithm of a graph by taking each vertex, traversing it, then skipping to the next vertex that hasn't already been assigned to a component.
This is the graph. The output I currently get is: [1, 1, 1, 1, 1, 0, 3, 3, 3, 3, 4, 4, 4]
Which shows mostly correct output except that neither v1 or v4 correctly call v5 to assign it a group, so it's recognized as it's own group. Not sure why this is the case.
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)