C / C++ Program for Dijkstra\'s shortest path algorithm

Dijkstra's algorithm is a greedy algorithm used to find the shortest path from a source vertex to all other vertices in a weighted graph. It works by maintaining a set of vertices whose shortest distance from the source has been determined and gradually expanding this set until all vertices are included.

Syntax

void dijkstra(int graph[V][V], int source);

Algorithm Steps

Step 1: Create a set to store vertices included in shortest path tree
Step 2: Initialize all distances as INFINITE and source distance as 0
Step 3: Loop until all vertices are processed:
   Step 3.1: Pick the unvisited vertex with minimum distance
   Step 3.2: Mark this vertex as visited
   Step 3.3: Update distances of all adjacent unvisited vertices

Example: Dijkstra's Algorithm Implementation

This example implements Dijkstra's algorithm using adjacency matrix representation −

#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

#define V 9

/* Function to find vertex with minimum distance from unvisited vertices */
int minDistance(int dist[], bool sptSet[]) {
    int min = INT_MAX, min_index;
    
    for (int v = 0; v < V; v++) {
        if (sptSet[v] == false && dist[v] <= min) {
            min = dist[v];
            min_index = v;
        }
    }
    return min_index;
}

/* Function to print the shortest distances */
void printSolution(int dist[]) {
    printf("Vertex   Distance from Source\n");
    for (int i = 0; i < V; i++) {
        printf("%d        %d\n", i, dist[i]);
    }
}

/* Dijkstra's algorithm implementation */
void dijkstra(int graph[V][V], int src) {
    int dist[V];      /* dist[i] holds shortest distance from src to i */
    bool sptSet[V];   /* sptSet[i] is true if vertex i is included in shortest path tree */
    
    /* Initialize all distances as INFINITE and sptSet[] as false */
    for (int i = 0; i < V; i++) {
        dist[i] = INT_MAX;
        sptSet[i] = false;
    }
    
    /* Distance from source to itself is always 0 */
    dist[src] = 0;
    
    /* Find shortest path for all vertices */
    for (int count = 0; count < V - 1; count++) {
        /* Pick minimum distance vertex from unvisited vertices */
        int u = minDistance(dist, sptSet);
        
        /* Mark the picked vertex as visited */
        sptSet[u] = true;
        
        /* Update dist value of adjacent vertices of picked vertex */
        for (int v = 0; v < V; v++) {
            if (!sptSet[v] && graph[u][v] && 
                dist[u] != INT_MAX && 
                dist[u] + graph[u][v] < dist[v]) {
                dist[v] = dist[u] + graph[u][v];
            }
        }
    }
    
    /* Print the shortest distances */
    printSolution(dist);
}

int main() {
    /* Example graph represented as adjacency matrix */
    int graph[V][V] = {
        { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
        { 6, 0, 8, 0, 0, 0, 0, 13, 0 },
        { 0, 8, 0, 7, 0, 6, 0, 0, 2 },
        { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
        { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
        { 0, 0, 6, 14, 10, 0, 2, 0, 0 },
        { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
        { 8, 13, 0, 0, 0, 0, 1, 0, 7 },
        { 0, 0, 2, 0, 0, 0, 6, 7, 0 }
    };
    
    printf("Dijkstra's Shortest Path Algorithm\n");
    printf("===================================\n");
    dijkstra(graph, 0);
    
    return 0;
}
Dijkstra's Shortest Path Algorithm
===================================
Vertex   Distance from Source
0        0
1        6
2        14
3        21
4        21
5        11
6        9
7        8
8        15

Key Points

  • Time Complexity: O(V²) for adjacency matrix representation
  • Space Complexity: O(V) for distance and visited arrays
  • Works only with non-negative edge weights
  • Uses greedy approach − always picks the closest unvisited vertex

Conclusion

Dijkstra's algorithm efficiently finds shortest paths from a source vertex to all other vertices in a weighted graph. It's widely used in network routing protocols and GPS navigation systems due to its optimal substructure property.

Updated on: 2026-03-15T12:27:44+05:30

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements