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