Facebook
From Chocolate Zebra, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 58
  1. graph = {
  2.   'A' : ['B','C'],
  3.   'B' : ['D', 'E'],
  4.   'C' : ['F'],
  5.   'D' : [],
  6.   'E' : ['F'],
  7.   'F' : []
  8. }
  9.  
  10. visited = [] # List to keep track of visited nodes.
  11. queue = []     #Initialize a queue
  12.  
  13. def bfs(visited, graph, node):
  14.   visited.append(node)
  15.   queue.append(node)
  16.  
  17.   while queue:
  18.     s = queue.pop(0)
  19.     print (s, end = " ")
  20.  
  21.     for neighbour in graph[s]:
  22.       if neighbour not in visited:
  23.         visited.append(neighbour)
  24.         queue.append(neighbour)
  25.  
  26. # Driver Code
  27. bfs(visited, graph, 'A')