fork download
  1. from collections import deque
  2.  
  3. graph = {
  4. 'A': ['B', 'C'],
  5. 'B': ['D', 'E'],
  6. 'C': ['F'],
  7. 'D': [],
  8. 'E': ['F'],
  9. 'F': []
  10. }
  11.  
  12. def bfs(graph, start):
  13. visited = []
  14. queue = deque([start])
  15. while queue:
  16. node = queue.popleft()
  17. if node not in visited:
  18. visited.append(node)
  19. queue.extend(graph[node])
  20. return visited
  21.  
  22. def dfs(graph, start):
  23. visited = []
  24. stack = [start]
  25. while stack:
  26. node = stack.pop()
  27. if node not in visited:
  28. visited.append(node)
  29. stack.extend(reversed(graph[node]))
  30. return visited
  31.  
  32. bfs_result = bfs(graph, 'A')
  33. dfs_result = dfs(graph, 'A')
  34.  
  35. print("BFS:", bfs_result)
  36. print("DFS:", dfs_result)
  37.  
Success #stdin #stdout 0.02s 7496KB
stdin
Standard input is empty
stdout
('BFS:', ['A', 'B', 'C', 'D', 'E', 'F'])
('DFS:', ['A', 'B', 'D', 'E', 'F', 'C'])