fork download
  1. graph = {
  2. 'A': ['B', 'C'],
  3. 'B': ['D'],
  4. 'C': [],
  5. 'D': [],
  6. 'E': ['F'], # 'E' and 'F' are disconnected from 'A'
  7. 'F': []
  8. }
  9.  
  10. source = 'A'
  11. visited = set()
  12. stack = [source]
  13.  
  14. print("DFS Traversal starting from node", source, ":")
  15.  
  16. while stack:
  17. x = stack.pop()
  18.  
  19. if x not in visited:
  20. visited.add(x)
  21. print(x, end=" ")
  22.  
  23. # Reverse neighbors before pushing so they are popped in natural left-to-right order
  24. for v in reversed(graph[x]):
  25. if v not in visited:
  26. stack.append(v)
Success #stdin #stdout 0.13s 14060KB
stdin
Standard input is empty
stdout
DFS Traversal starting from node A :
A B D C