fork download
  1. graph = {'5' : ['3','7'],'3' : ['2', '4'],'7' : ['8'],'2' : [],'4' : ['8'],'8' : []}
  2. visited = set()
  3. def dfs(visited, graph, node):
  4. if node not in visited:
  5. print (node)
  6. visited.add(node)
  7. for neighbour in graph[node]:
  8. dfs(visited, graph, neighbour)
  9. print("Following is the Depth-First Search")
  10. dfs(visited, graph, '5')
Success #stdin #stdout 0.03s 25472KB
stdin
Standard input is empty
stdout
graph = {'5' : ['3','7'],'3' : ['2', '4'],'7' : ['8'],'2' : [],'4' : ['8'],'8' : []}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("Following is the Depth-First Search")
dfs(visited, graph, '5')