Skip to content

Commit 77130a9

Browse files
Added implementation of djikstra's shortest path algo.
1 parent 3632487 commit 77130a9

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

djikstras_shortest_path.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Author: Jay Paliwal
3+
Desc: Implementation fo graph using adjecency matrix and calculation
4+
of the length of the shortest path using dijkstra's algorithm
5+
"""
6+
7+
import sys
8+
9+
class Graph:
10+
def __init__(self,vertices):
11+
self.vertices=vertices
12+
self.graph=[[0]*vertices]*vertices
13+
14+
def add_edge(self,v1,v2,wt):
15+
self.graph[v1][v2]=wt
16+
self.graph[v2][v1]=wt
17+
18+
def dijkstra(self,src,dest):
19+
d=[sys.maxsize]*self.vertices
20+
d[src]=0
21+
shrtst_pth=[False]*self.vertices
22+
for _ in range(self.vertices):
23+
min=sys.maxsize
24+
for i in range(self.vertices):
25+
if d[i]<min and shrtst_pth[i]==False:
26+
min=d[i]
27+
v1=i
28+
shrtst_pth[v1]=True
29+
for v2 in range(self.vertices):
30+
if self.graph[v1][v2]>0 and shrtst_pth[v2]==False and d[v2]>(d[v1]+self.graph[v1][v2]):
31+
d[v2]=d[v1]+self.graph[v1][v2]
32+
print("The length of the shortest path between ",src," and ",dest," is: ",d[dest]
33+
34+
v=int(input("Enter the number of vertices: "))
35+
g=Graph(v)
36+
c='1'
37+
while True:
38+
c=input("Enter '1' to add a new edge, enter '0' if you are done adding edges: ")
39+
if c!='0' or c!='1':
40+
print("Invalid input")
41+
continue
42+
elif c=='0':
43+
break
44+
a=int(input("Enter first vertex: "))
45+
b=int(input("Enter second vertex: "))
46+
if a>=v or a<0:
47+
print("Invalid value entered for first vertex")
48+
continue
49+
if b>=v or b<0:
50+
print("Invalid value entered for second vertex")
51+
continue
52+
wt=int(input("Enter the weight of the edge: "))
53+
g.add_edge(a,b,wt)
54+
55+
while True:
56+
src,dest=map(int,input("Enter the source and destination vertex to calculate the shorthest path (source followed by destination): ").rstrip().split())
57+
if (src>=0 and src<v) and (dest>=0 and dest<v):
58+
break
59+
print("Invalid input.")
60+
61+
g.dijkstra(src,dest)

0 commit comments

Comments
 (0)