I am trying to write a recursive depth-first search algorithm that takes an adjacency list representing a graph and prints the visit order of the vertices.
My input is a graph stored as an adjacency list:
graphAL2 = {0 : [1,2,3],
1 : [0,3,4],
2 : [0,4,5],
3 : [0,1,5],
4 : [1,2],
5 : [2,3] }
From there, I have written 2 functions, a main and a secondary function, that make up the program.
import sys
def main():
count = 0
graphAL2v = {}
for key, value in graphAL2.items():
graphAL2v[key] = 0
print graphAL2v
for key in graphAL2v:
if key == 0:
dfs(key, count, graphAL2v)
def dfs(v, count, graph):
count = count + 1
graph[v] = count
for key in graph:
if key == 0:
dfs(key, count, graph)
if __name__ == "__main__":
sys.exit(main())
Right now my if I run it, the output is:
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
{0: 1, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
and the first value paired with key 0 keeps incrementing until a
RuntimeError: maximum recursion depth exceeded
is reached. The for loop should be going through the rest of the key-pair values and changing the values to the order that the vertex was visited but I'm not sure why it isn't doing so.
Any thoughts?