Advertisement
romakoch

Untitled

Oct 3rd, 2020
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. graph = {
  2.     1: [2,3],
  3.     2: [1,4,5],
  4.     3: [1,6,7],
  5.     4: [2],
  6.     5: [2],
  7.     6: [3],
  8.     7: [3],
  9. }
  10. def bfs(graph, initial, goal):
  11.    
  12.     visited = []
  13.     queue = [initial]
  14.    
  15.     while queue:
  16.         node = queue.pop(0)
  17.         if node not in visited:
  18.            
  19.             visited.append(node)
  20.             print('The node is:' + str(node))
  21.  
  22.             if node == goal:
  23.                 print('Goal node '+ '"' + str(node) + '"' +' is founded')
  24.                 return visited
  25.  
  26.             neighbours = graph[node]
  27.             print('The neighbours of the node ' + str(node) + ' are: ' + str(neighbours))
  28.             print('The visited nodes: ' + str(visited) + '\n')
  29.  
  30.             for neighbour in neighbours:
  31.                 if neighbour not in visited:
  32.                     queue.append(neighbour)
  33.                     print('Appending to queue ' + str(neighbour) + '...')
  34.  
  35.             print('The visited nodes: ' + str(visited) )
  36.             print('The queue now: ' + str(queue)+ '\n')
  37.  
  38.     return visited
  39.  
  40. print(bfs(graph, 1, 7));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement