BellmanFord.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. import sys
  4. inf = float('inf')
  5. #function that performs Bellman-Ford algorithm on the graph G,with source vertex as source
  6. def bellmanFord(G, source, pos):
  7. V = len(G.nodes()) # V denotes the number of vertices in G
  8. dist = [] # dist[i] will hold the shortest distance from source to i
  9. parent = [None]*V # parent[i] will hold the node from which i is reached to, in the shortest path from source
  10. for i in range(V):
  11. dist.append(inf)
  12. parent[source] = -1; #source is itself the root, and hence has no parent
  13. dist[source] = 0;
  14. for i in range(V-1):
  15. for u, v, d in G.edges(data = True): # Relaxation is the most important step in Bellman-Ford. It is what increases the accuracy of the distance to any given vertex. Relaxation works by continuously shortening the calculated distance between vertices comparing that distance with other known distances.
  16. if dist[u] + d['length'] < dist[v]: #Relaxation Equation
  17. dist[v] = d['length'] + dist[u]
  18. parent[v] = u
  19. #marking the shortest path from source to each of the vertex with red, using parent[]
  20. for v in range(V):
  21. if parent[v] != -1: #ignore the parent of root node
  22. if (parent[v], v) in G.edges():
  23. nx.draw_networkx_edges(G, pos, edgelist = [(parent[v], v)], width = 2.5, alpha = 0.6, edge_color = 'r')
  24. return
  25. #takes input from the file and creates a weighted graph
  26. def createGraph():
  27. G = nx.DiGraph()
  28. f = open('input.txt')
  29. n = int(f.readline())
  30. wtMatrix = []
  31. for i in range(n):
  32. list1 = map(int, (f.readline()).split())
  33. wtMatrix.append(list1)
  34. source = int(f.readline()) #source vertex for BellmanFord algo
  35. #Adds egdes along with their weights to the graph
  36. for i in range(n) :
  37. for j in range(n) :
  38. if wtMatrix[i][j] > 0 :
  39. G.add_edge(i, j, length = wtMatrix[i][j])
  40. return G, source
  41. #draws the graph and displays the weights on the edges
  42. def DrawGraph(G):
  43. pos = nx.spring_layout(G)
  44. nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
  45. edge_labels = dict([((u, v), d['length']) for u, v, d in G.edges(data = True)])
  46. nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
  47. return pos
  48. #main function
  49. if __name__ == "__main__":
  50. G, source = createGraph()
  51. pos = DrawGraph(G)
  52. bellmanFord(G, source, pos)
  53. plt.show()