0% found this document useful (0 votes)
52 views2 pages

Aim: Write A Program To Find Out The Shortest Path Using Dijsktra Algorithm Program

This document contains a Python program to find the shortest path between nodes in a graph using Dijkstra's algorithm. The program takes the number of nodes, a source node, and a cost matrix as input. It initializes distance values and flags, then iterates to find the minimum distance node and update distances until all nodes are reached. It outputs the shortest path and cost from the source to each other node.

Uploaded by

Ali Baig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views2 pages

Aim: Write A Program To Find Out The Shortest Path Using Dijsktra Algorithm Program

This document contains a Python program to find the shortest path between nodes in a graph using Dijkstra's algorithm. The program takes the number of nodes, a source node, and a cost matrix as input. It initializes distance values and flags, then iterates to find the minimum distance node and update distances until all nodes are reached. It outputs the shortest path and cost from the source to each other node.

Uploaded by

Ali Baig
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 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