Facebook
From Bistre Earthworm, 4 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 125
  1. graph = {'A' : ['E','D','F','B'],
  2.          'B' : ['A','G','H','C'],
  3.          'C' : ['B'],
  4.          'D' : ['A'],
  5.          'E' : ['A'],
  6.          'F' : ['A'],
  7.          'G' : ['B'],
  8.          'H' : ['B']
  9.          }
  10.  
  11. def BFS(graph,node):
  12.     visited=[]
  13.     queue=[]
  14.     visited.append(node)
  15.     queue.append(node)
  16.  
  17.     while queue:
  18.         node=queue.pop(0)
  19.         print(node)
  20.  
  21.         for i in graph[node]:
  22.             if i not in visited:
  23.                 visited.append(i)
  24.                 queue.append(i)
  25.  
  26.  
  27. def DFS(graph,node):
  28.     visited=[]
  29.     stack=[]
  30.     visited.append(node)
  31.     stack.append(node)
  32.  
  33.     while stack:
  34.         node=stack.pop()
  35.         print(node)
  36.  
  37.         for i in graph[node]:
  38.             if i not in visited:
  39.                 visited.append(i)
  40.                 stack.append(i)
  41.  
  42. print('BFS')
  43. BFS(graph,'A')
  44. print('DFS')
  45. DFS(graph,'A')
  46.