0% found this document useful (0 votes)
6 views

Dsaex 12

Uploaded by

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

Dsaex 12

Uploaded by

saran2732006s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Ex No: 12 IMPLEMENTATION OF DJIKSTRA’S

20/05/2024 ALGORITHM

Implement shortest path algorithm (Dijkstra’s algorithm)


Aim:
To write a program to find the shortest path from source node to every node

Program:
#include <stdio.h>
#include <limits.h>

#define MAX 100


#define INF INT_MAX

int adj[MAX][MAX];
int distance[MAX];
int visited[MAX];
int n;

int minDistance()
{
int min = INF, min_index;
for (int v = 0; v < n; v++)
{
if (visited[v] == 0 && distance[v] <= min)
{
min = distance[v], min_index = v;
}
}
return min_index;
}
void dijkstra(int src)
{
for (int i = 0; i < n; i++)
{
distance[i] = INF;
visited[i] = 0;
}
distance[src] = 0;
for (int count = 0; count < n - 1; count++)
{
int u = minDistance();
visited[u] = 1;
for (int v = 0; v < n; v++)
{
if (!visited[v] && adj[u][v] && distance[u] != INF && distance[u] + adj[u][v] <
distance[v])
{
distance[v] = distance[u] + adj[u][v];
}
}
}
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < n; i++)
{
printf("%d \t %d\n", i, distance[i]);
}
}

int main()
{
int i, j, edges, origin, destin, weight;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
adj[i][j] = 0;
}
}

printf("Enter the number of edges: ");


scanf("%d", &edges);
for (i = 0; i < edges; i++)
{
printf("Enter edge (origin destination weight): ");
scanf("%d %d %d", &origin, &destin, &weight);
if (origin >= n || destin >= n || origin < 0 || destin < 0)
{
printf("Invalid edge!\n");
i--;
}
else
{
adj[origin][destin] = weight;
adj[destin][origin] = weight; // If the graph is undirected
}
}

int startVertex;
printf("Enter the starting vertex for Dijkstra's algorithm: ");
scanf("%d", &startVertex);

dijkstra(startVertex);

return 0;
}

Output:

Result:
The above program was successfully executed and the shortest path from the source
were calculated.

You might also like