/*PROGRAM 4
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>
#include <stdlib.h>
#define INFINITY INT_MAX
void dij(int n, int v, int cost[10][10], int dist[10]) {
int i, u, count, w, flag[10], min;
for(i = 0; i< n; i++) {
flag[i] = 0; // No node is visited initially
dist[i] = cost[v][i]; // Distance from the source node to each node
count = 1;
flag[v] = 1; // Mark the source node as visited
while(count < n) {
min = INFINITY;
// Find the node with the minimum distance
for(w = 0; w < n; w++)
if(dist[w] < min && !flag[w]) {
min = dist[w];
u = w;
// Mark the node as visited
flag[u] = 1;
count++;
// Update the distances of the neighbors of the chosen node
for(w = 0; w < n; w++)
if((dist[u] + cost[u][w] <dist[w]) && !flag[w])
dist[w] = dist[u] + cost[u][w];
int main() {
int n, v, i, j, cost[10][10], dist[10];
// Input the number of nodes
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
// Input the cost matrix
printf("\nEnter the cost matrix:\n");
for(i = 0; i< n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &cost[i][j]);
if(cost[i][j] == 0 &&i != j) // If no path exists, set it to infinity
cost[i][j] = INFINITY;
}
}
// Input the source node
printf("\nEnter the source node: ");
scanf("%d", &v);
v--;
dij(n, v, cost, dist);
// Output the shortest paths from the source node
printf("\nShortest paths from node %d:\n", v + 1);
for(i = 0; i< n; i++) {
if(i != v) // Skip the source node itself
printf("%d -> %d, cost = %d\n", v + 1, i + 1, dist[i]);
return 0;