document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. def printBfsLevels(graph,start):
  2.   queue=[start]
  3.   path=[]
  4.   currLevel=1
  5.   levelMembers=1
  6.   height=[(0,start)]
  7.   childCount=0
  8.   print queue
  9.   while queue:
  10.     visNode=queue.pop(0)
  11.     if visNode not in path:
  12.       if  levelMembers==0:
  13.         levelMembers=childCount
  14.         childCount=0
  15.         currLevel=currLevel+1
  16.       queue=queue+graph.get(visNode,[])
  17.       if levelMembers > 0:
  18.         levelMembers=levelMembers-1
  19.         for node in graph.get(visNode,[]):
  20.           childCount=childCount+1
  21.           height.append((currLevel,node))
  22.       path=path+[visNode]
  23.  
  24.   prevLevel=None
  25.  
  26.   for v,k in sorted(height):
  27.         if prevLevel!=v:
  28.           if prevLevel!=None:
  29.             print "\\n"
  30.         prevLevel=v
  31.         print k,
  32.   return height
  33.  
  34. g={1: [2, 3,6], 2: [4, 5], 3: [6, 7],4:[8,9,13]}
  35. printBfsLevels(g,1)
  36.  
  37.  
  38. >>>
  39. [1]
  40. 1
  41.  
  42. 2 3 6
  43.  
  44. 4 5 6 7
  45.  
  46. 8 9 13
  47. >>>
');