Program
#include <stdio.h>
#include <conio.h>
void dij(int, int[20][20], int[20], int[20], int);
void main()
{
int i, j, n, visited[20], source, cost[20][20], d[20];
printf("****************************************************************");
printf("\n****************************************************************");
printf("\n** WAP to find shortest path from a single source to all nodes**");
printf("\n** using Dijikstra's Algorithm in C **");
printf("\n** Created by Sheetal Garg **");
printf("\n** Assistant Professor **");
printf("\n** Phone No:9467863365 **");
printf("\n****************************************************************");
printf("\n****************************************************************");
printf("\nEnter no. of vertices: ");
scanf("%d", &n);
printf("Enter the cost adjacency matrix\n");
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%d", &cost[i][j]);
}
}
printf("\nEnter the source node: ");
scanf("%d", &source);
dij(source, cost, visited, d, n);
for (i = 1; i <= n; i++)
if (i != source)
printf("\nShortest path from %d to %d is %d", source, i, d[i]);
getch();
}
void dij(int source, int cost[20][20], int visited[20], int d[20], int n)
{
int i, j, min, u, w;
for (i = 1; i <= n; i++)
{
visited[i] = 0;
d[i] = cost[i];
}
visited = 1;
d = 0;
for (j = 2; j <= n; j++)
{
min = 999;
for (i = 1; i <= n; i++)
{
if (!visited[i])
{
if (d[i] < min)
{
min = d[i];
u = i;
}
}
}
visited[u] = 1;
for (w = 1; w <= n; w++)
{
if (cost[u][w] != 999 && visited[w] == 0)
{
if (d[w] > cost[u][w] + d[u])
d[w] = cost[u][w] + d[u];
}
} // for w
} // for j
}
Output
**************************************************************** **************************************************************** ** WAP to find shortest path from a single source to all nodes** ** using Dijikstra's Algorithm in C ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************************** **************************************************************** Enter no. of vertices: 4 Enter the cost adjacency matrix 2 4 5 1 4 6 2 3 45 6 5 1 3 4 6 0 Enter the source node: 1 Shortest path from 1 to 2 is 4 Shortest path from 1 to 3 is 5 Shortest path from 1 to 4 is 1