Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.2 KiB

  1. # Python program for Dijkstra's single
  2. # source shortest path algorithm. The program is
  3. # for adjacency matrix representation of the graph
  4. # Library for INT_MAX
  5. import sys
  6. class Graph():
  7. def __init__(self, vertices):
  8. self.V = vertices
  9. self.graph = [[0 for column in range(vertices)]
  10. for row in range(vertices)]
  11. def printSolution(self, dist):
  12. print "Vertex tDistance from Source"
  13. for node in range(self.V):
  14. print node, "t", dist[node]
  15. # A utility function to find the vertex with
  16. # minimum distance value, from the set of vertices
  17. # not yet included in shortest path tree
  18. def minDistance(self, dist, sptSet):
  19. # Initilaize minimum distance for next node
  20. min = sys.maxint
  21. # Search not nearest vertex not in the
  22. # shortest path tree
  23. for v in range(self.V):
  24. if dist[v] < min and sptSet[v] == False:
  25. min = dist[v]
  26. min_index = v
  27. return min_index
  28. # Funtion that implements Dijkstra's single source
  29. # shortest path algorithm for a graph represented
  30. # using adjacency matrix representation
  31. def dijkstra(self, src):
  32. dist = [sys.maxint] * self.V
  33. dist[src] = 0
  34. sptSet = [False] * self.V
  35. for cout in range(self.V):
  36. # Pick the minimum distance vertex from
  37. # the set of vertices not yet processed.
  38. # u is always equal to src in first iteration
  39. u = self.minDistance(dist, sptSet)
  40. # Put the minimum distance vertex in the
  41. # shotest path tree
  42. sptSet[u] = True
  43. # Update dist value of the adjacent vertices
  44. # of the picked vertex only if the current
  45. # distance is greater than new distance and
  46. # the vertex in not in the shotest path tree
  47. for v in range(self.V):
  48. if self.graph[u][v] > 0 and sptSet[v] == False and \
  49. dist[v] > dist[u] + self.graph[u][v]:
  50. dist[v] = dist[u] + self.graph[u][v]
  51. self.printSolution(dist)
  52. # Driver program
  53. g = Graph(9)
  54. g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
  55. [4, 0, 8, 0, 0, 0, 0, 11, 0],
  56. [0, 8, 0, 7, 0, 4, 0, 0, 2],
  57. [0, 0, 7, 0, 9, 14, 0, 0, 0],
  58. [0, 0, 0, 9, 0, 10, 0, 0, 0],
  59. [0, 0, 4, 14, 10, 0, 2, 0, 0],
  60. [0, 0, 0, 0, 0, 2, 0, 1, 6],
  61. [8, 11, 0, 0, 0, 0, 1, 0, 7],
  62. [0, 0, 2, 0, 0, 0, 6, 7, 0]
  63. ];
  64. g.dijkstra(0);