Dijkstra’s Algorithm to find Shortest Path for the given graph:-
Program:-
#include <stdio.h>
#define MAX 15
#define INFINITY 20
void dij(int s);
void create_graph();
void display();
void path();
int s, n, cost[MAX][MAX], dist[MAX], prefix[MAX];
int main() {
int i;
create_graph();
printf("\n Enter the source element: ");
scanf("%d", &s);
dij(s);
printf("\n Shortest paths: \n");
display();
path();
getchar(); // Pause the program and wait for a key press
return 0;
void create_graph() {
int i, j;
printf("\n Enter the no.of nodes: ");
scanf("%d", &n);
printf("\n Enter the cost matrix: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
cost[i][j] = INFINITY;
void dij(int v) {
int u, i, j, k, count, w, permanent[MAX], min, p;
for (i = 1; i <= n; i++) {
permanent[i] = 0;
dist[i] = cost[v][i];
if (dist[i] != INFINITY)
prefix[i] = v;
permanent[v] = 1;
dist[v] = 0;
for (i = 0; i < n - 1; i++) {
min = INFINITY;
for (w = 1; w <= n; w++)
if (dist[w] < min && !permanent[w]) {
min = dist[w];
u = w;
permanent[u] = 1;
for (w = 1; w <= n; w++)
if (dist[u] + cost[u][w] < dist[w] && !permanent[w]) {
dist[w] = dist[u] + cost[u][w];
prefix[w] = u;
}
}
void display() {
int i;
printf("\n Vertex->Vertex via distance \n");
for (i = 1; i <= n; i++)
printf("%6d->%d\tvia %d\t%d\n", s, i, prefix[i], dist[i]);
void path() {
int i, j;
for (i = 1; i <= n; i++) {
printf("%d ", i);
j = prefix[i];
while (j != 0) {
printf("<-- %d ", j);
j = prefix[j];
printf("\n");
Output:-
Enter the no.of nodes: 3
Enter the cost matrix:
123
215
123
Enter the source element: 2
Shortest paths:
Vertex->Vertex via distance
2->1 via 2 2
2->2 via 2 0
2->3 via 2 5
1 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <--
2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <-- 2 <