I am trying to come up with a greedy algorithm in Python that returns the vertices in an undirected graph given a certain starting vertex. I understand that DFS determines if a cycle exists, but I am trying to actually return the vertices that form the cycle. I am using an adjacency matrix to represent the following graph:
adjacencyMatrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
pictorially this is an undirected graph comprised of a single cycle.
My current thought process is to set my starting index to the first 1
I come across (In this case adjacencyMatrix[0][1]
). Then I would look at the rest of the row to see if another 1
was there, because that means my current vertex is connected to that index. However, I am not entirely sure if (a) this is the right approach and (b) how to "move" to the next vertex. For example, how would I navigate my nested for
loop to move from the adjacencyMatrix[0][1]
vertex to the adjacencyMatrix[0][2]
vertex? Would I just swap the row and column indices?
EDIT This solution I came up with seems to work for the few graphs I tried it on:
def findCycle(matrix):
visited = list()
cycleNotFound = True
row = 0
col = 0
startVertex = (0, 0)
while cycleNotFound:
# Only add a vertex if it has not already been visited
if (matrix[row][col] == 1) and ((row, col) not in visited):
# Set the startVertex when the first node is found
if len(visited) == 0:
startVertex = (row, col)
# Add the current vertex and its counter part
visited.append((row, col))
visited.append((col, row))
# If row and col are equal, infite loop will get created
if row != col:
row = col
col = 0
else:
row += 1
# If back at starting point, break look
elif ((row, col) == startVertex) and (len(visited) > 1):
cycleNotFound = False
visited.append(startVertex)
# Else, continue to look for unvisted neighbors
else:
col += 1
return visited
if __name__ == "__main__":
matrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
cycle = findCycle(matrix)
index = 0
# Print the vertices. Only print even vertices to avoid duplicates.
while (index < len(cycle)):
print cycle[index]
index += 2
it is not the most elegant solution and I'm sure there is some major refactoring that needs to be done.