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

Dijkstras Algorithm

dsa program

Uploaded by

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

Dijkstras Algorithm

dsa program

Uploaded by

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

#include <stdio.

h>
#include <limits.h>
#define V 5
int findMinDist(int dist[], int visited[]) {
int min = INT_MAX, minIndex;
for (int v = 0; v < V; v++)
if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
return minIndex;
}
void printDistances(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
int visited[V] = {0};
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
for (int i = 0; i < V - 1; i++) {
int u = findMinDist(dist, visited);
visited[u] = 1;
for (int v = 0; v < V; v++)
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printDistances(dist);
}
int main() {
int graph[V][V] = {
{0, 10, 0, 5, 0},
{0, 0, 1, 2, 0},
{0, 0, 0, 0, 4},
{0, 3, 9, 0, 2},
{7, 0, 6, 0, 0}
};
dijkstra(graph, 0);
return 0;
}

OUTPUT:

You might also like