I'm currently getting to grips with graph traversal in Python.
Given the following graph:
Implemented using this dictionary:
graph = {'0': set(['1', '2', '3']),
'1': set(['0','2']),
'2': set(['0','1','4']),
'3': set(['0']),
'4': set(['2'])}
Am I correct in thinking a depth first search traversal beginning from node 0 should return [0,1,2,4,3]?
My dfs function returns [0,3,1,2,4] and so I am wondering if I have something wrong in my implementation:
def dfs(graph, node,visited=None):
if visited is None:
visited=set()
if node not in visited:
print (node,end=' ')
visited.add(node)
for neighbour in graph[node]:
dfs(graph,neighbour,visited=visited)
dfs(graph,'0')
Help and advice appreciated.
