MCPcopy Create free account
hub / github.com/SR-Sunny-Raj/Hacktoberfest2021-DSA / Graph

Class Graph

33. Python Programs/shortestpathWeightedGraph.py:3–61  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected