You are on page 1of 2

Aim: Write a program to find out the shortest path using dijsktra algorithm

Program:
def dij(n, v, cost):
flag=[i for i in range (n+1)]
u=0
for i in range (1,n+1):
flag[i]=0
dist[i]=cost[v][i]

count=2
while(count<=n):
min=99
for w in range (1,n+1):

if (dist[w]<min and not(flag[w])):


min=dist[w]
u=w
flag[u]=1
count+=1
for w in range (1,n+1):
if(dist[u]+cost[u][w]<dist[w] and not(flag[w])):
dist[w]=dist[u]+cost[u][w]
n=input('Enter number of nodes:')
print('Enter cost matrix:')
#cost=[[0,3,999,7],[3,0,4,2],[999,4,0,5],[7,2,5,0]]
cost = {i:{} for i in range(n+1)}
dist=[i for i in range (n+1)]
for i in range (1,n+1):
for j in range(1,n+1):
cost[i][j]=input()
j+=1
i+=1
v=input('Enter the source:')
dij(n,v,cost)
print('shortest path:')
for i in range(1,n+1):
if(i!=v):
print('{0}->{1},cost={2}'.format(v,i,dist[i]))

Output:
Enter number of nodes:4
Enter cost matrix:
0
3
999
7
3
0
4
2
999
4
0
5
7
2
5
0
Enter the source:1
shortest path:
1->2,cost=3
1->3,cost=7
1->4,cost=5

You might also like