bfs.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. #BFS traversal
  4. def BFS(G, source, pos):
  5. visited = [False]*(len(G.nodes()))
  6. queue = [] #a queue for BFS traversal
  7. queue.append(source)
  8. visited[source] = True
  9. while queue:
  10. curr_node = queue.pop(0)
  11. for i in G[curr_node]: #iterates through all the possible vertices adjacent to the curr_node
  12. if visited[i] == False:
  13. queue.append(i)
  14. visited[i] = True
  15. # nx.draw_networkx_edges(G, pos, edgelist = [(curr_node,i)], width = 2.5, alpha = 0.6, edge_color = 'r')
  16. return
  17. #takes input from the file and creates a weighted graph
  18. def CreateGraph():
  19. G = nx.DiGraph()
  20. f = open('input.txt')
  21. n = int(f.readline())
  22. wtMatrix = []
  23. for i in range(n):
  24. list1 = list(map(int, (f.readline()).split()))
  25. wtMatrix.append(list1)
  26. source = int(f.readline()) #source vertex from where BFS has to start
  27. #Adds egdes along with their weights to the graph
  28. for i in range(n):
  29. for j in range(len(wtMatrix[i])):
  30. if wtMatrix[i][j] > 0:
  31. G.add_edge(i, j, length = wtMatrix[i][j])
  32. return G, source
  33. #draws the graph and displays the weights on the edges
  34. def DrawGraph(G):
  35. pos = nx.spring_layout(G)
  36. nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
  37. edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
  38. nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
  39. return pos
  40. #main function
  41. if __name__== "__main__":
  42. G,source = CreateGraph()
  43. pos = DrawGraph(G)
  44. BFS(G, source, pos)
  45. plt.show()