The Shortest Path in a graph refers to finding the minimum distance between two nodes. This is crucial in routing, navigation, and optimization problems.
#include <stdio.h>
#include <limits.h>
#define V 5
int minDistance(int dist[], int visited[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (!visited[v] && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void dijkstra(int graph[V][V], int src) {
int dist[V]; // Shortest distance from src to i
int visited[V]; // True if vertex i is finalized
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(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];
}
printf("Vertex\tDistance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
dijkstra(graph, 0);
return 0;
}
Vertex Distance from Source 0 0 1 2 2 5 3 6 4 7
Used in GPS systems, routing in networks, and many path-finding problems in games and robotics.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!