DJ Algoritm
DJ Algoritm
DJ Algoritm
Dijkstra’s Algorithm
Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra’s algorithm.
#include <stdio.h>
#include <limits.h>
min = dist[v];
minIndex = v;
return minIndex;
// Function to implement Dijkstra's algorithm for a given graph and source vertex
int dist[MAX_VERTICES]; // The output array dist[i] holds the shortest distance from src to i
int sptSet[MAX_VERTICES]; // sptSet[i] will be true if vertex i is included in the shortest path
tree or the shortest distance from src to i is finalized
dist[i] = INT_MAX;
sptSet[i] = 0;
dist[src] = 0;
// Pick the minimum distance vertex from the set of vertices not yet processed.
sptSet[u] = 1;
// and the total weight of path from src to v through u is smaller than the current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
printSolution(dist, vertices);
}
int main() {
int vertices;
scanf("%d", &vertices);
return 1;
int graph[MAX_VERTICES][MAX_VERTICES];
printf("Input the adjacency matrix for the graph (use INT_MAX for infinity):\n");
scanf("%d", &graph[i][j]);
} }
int source;
scanf("%d", &source);
return 1;
return 0;
}
OUTPUT:
Input the number of vertices: 5
Input the adjacency matrix for the graph (use INT_MAX for infinity):
03200
30010
20014
01102
00420
Input the source vertex: 0
Vertex Distance from Source
0 0
1 3
2 2
3 3
4 5
Explanation:
minDistance Function:
o It finds the vertex with the minimum distance value from the source
vertex that has not been processed yet.
o Parameters:
dist: Array holding the distance values from the source vertex.
printSolution Function:
o Parameters:
dist: Array holding the distance values from the source vertex.
dijkstra Function:
o Parameters:
Picks the vertex with the minimum distance from the set of
vertices not yet processed.
main Function:
o It takes input for the number of vertices, the adjacency matrix, and the
source vertex.