From d280651003c1d72782e70defb1bf84c4cb6d5c6d Mon Sep 17 00:00:00 2001 From: Pratik Kumar Mohanty <81863504+pkmpratik@users.noreply.github.com> Date: Mon, 3 Oct 2022 19:34:15 +0530 Subject: [PATCH] Dijkastra's solution --- .../Python_Programs/Dijkastra's solution.py | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Program's_Contributed_By_Contributors/Python_Programs/Dijkastra's solution.py diff --git a/Program's_Contributed_By_Contributors/Python_Programs/Dijkastra's solution.py b/Program's_Contributed_By_Contributors/Python_Programs/Dijkastra's solution.py new file mode 100644 index 0000000000..7efe8f765d --- /dev/null +++ b/Program's_Contributed_By_Contributors/Python_Programs/Dijkastra's solution.py @@ -0,0 +1,78 @@ +# Python program for Dijkstra's single +# source shortest path algorithm. The program is +# for adjacency matrix representation of the graph +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + + def printSolution(self, dist): + print("Vertex \t Distance from Source") + for node in range(self.V): + print(node, "\t\t", dist[node]) + + # A utility function to find the vertex with + # minimum distance value, from the set of vertices + # not yet included in shortest path tree + def minDistance(self, dist, sptSet): + + # Initialize minimum distance for next node + min = 1e7 + + # Search not nearest vertex not in the + # shortest path tree + for v in range(self.V): + if dist[v] < min and sptSet[v] == False: + min = dist[v] + min_index = v + + return min_index + + # Function that implements Dijkstra's single source + # shortest path algorithm for a graph represented + # using adjacency matrix representation + def dijkstra(self, src): + + dist = [1e7] * self.V + dist[src] = 0 + sptSet = [False] * self.V + + for cout in range(self.V): + + # Pick the minimum distance vertex from + # the set of vertices not yet processed. + # u is always equal to src in first iteration + u = self.minDistance(dist, sptSet) + + # Put the minimum distance vertex in the + # shortest path tree + sptSet[u] = True + + # Update dist value of the adjacent vertices + # of the picked vertex only if the current + # distance is greater than new distance and + # the vertex in not in the shortest path tree + for v in range(self.V): + if (self.graph[u][v] > 0 and + sptSet[v] == False and + dist[v] > dist[u] + self.graph[u][v]): + dist[v] = dist[u] + self.graph[u][v] + + self.printSolution(dist) + +# Driver program +g = Graph(9) +g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], + [4, 0, 8, 0, 0, 0, 0, 11, 0], + [0, 8, 0, 7, 0, 4, 0, 0, 2], + [0, 0, 7, 0, 9, 14, 0, 0, 0], + [0, 0, 0, 9, 0, 10, 0, 0, 0], + [0, 0, 4, 14, 10, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 2, 0, 1, 6], + [8, 11, 0, 0, 0, 0, 1, 0, 7], + [0, 0, 2, 0, 0, 0, 6, 7, 0] + ] + +g.dijkstra(0)