1+ import sys
2+ def to_be_visited ():
3+ global visited_and_distance
4+ v = - 10
5+ for index in range (number_of_vertices ):
6+ if visited_and_distance [index ][0 ] == 0 \
7+ and (v < 0 or visited_and_distance [index ][1 ] <= \
8+ visited_and_distance [v ][1 ]):
9+ v = index
10+ return v
11+ vertices = [[0 , 1 , 1 , 0 ],
12+ [0 , 0 , 1 , 0 ],
13+ [0 , 0 , 0 , 1 ],
14+ [0 , 0 , 0 , 0 ]]
15+ edges = [[0 , 3 , 4 , 0 ],
16+ [0 , 0 , 0.5 , 0 ],
17+ [0 , 0 , 0 , 1 ],
18+ [0 , 0 , 0 , 0 ]]
19+
20+ number_of_vertices = len (vertices [0 ])
21+ visited_and_distance = [[0 , 0 ]]
22+ for i in range (number_of_vertices - 1 ):
23+ visited_and_distance .append ([0 , sys .maxsize ])
24+
25+ for vertex in range (number_of_vertices ):
26+ to_visit = to_be_visited ()
27+ for neighbor_index in range (number_of_vertices ):
28+ if vertices [to_visit ][neighbor_index ] == 1 and \
29+ visited_and_distance [neighbor_index ][0 ] == 0 :
30+ new_distance = visited_and_distance [to_visit ][1 ] \
31+ + edges [to_visit ][neighbor_index ]
32+ if visited_and_distance [neighbor_index ][1 ] > new_distance :
33+ visited_and_distance [neighbor_index ][1 ] = new_distance
34+ visited_and_distance [to_visit ][0 ] = 1
35+
36+ i = 0
37+
38+ for distance in visited_and_distance :
39+ print ("The shortest distance of " ,chr (ord ('a' ) + i ),\
40+ " from the source vertex a is:" ,distance [1 ])
41+ i = i + 1
0 commit comments