Reading history

Dijkstra’s Shortest Path Algorithm in C

5 min read 1 views

Learn Dijkstra's algorithm in C: greedy selection, edge relaxation, rebuilding the route, complexity with arrays and heaps, and negative weights.

Dijkstra’s algorithm finds the shortest path from one starting vertex to every other vertex in a graph whose edges have non-negative weights, such as road lengths or travel times. It is the idea behind route planners and network routing. The algorithm repeatedly settles the closest vertex it has not finished yet and uses it to improve the distances to that vertex’s neighbours.

In this lesson you will learn

  • The greedy idea behind Dijkstra’s algorithm
  • Edge “relaxation”
  • A complete C implementation on a weighted adjacency matrix
  • Rebuilding the actual route, not just its length
  • Complexity, and why negative weights break it

How It Works

  1. Set the distance to the start as 0 and every other distance as infinity.
  2. Pick the unfinished vertex with the smallest known distance and mark it finished. Its distance is now final.
  3. Relax each of its edges: if going through this vertex gives a shorter route to a neighbour, update that neighbour’s distance and remember where it came from.
  4. Repeat until every reachable vertex is finished.

The method is greedy: it always commits to the closest vertex. That is safe because, with no negative edges, no later detour can make a finished vertex closer.

Dijkstra’s Algorithm in C

The graph has six towns, A to F; each number in the matrix is the length of the road between two towns.

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

#define V 6
#define INF INT_MAX

/* Weighted graph: graph[u][v] is the road length, 0 means no road */
int graph[V][V] = {
    /*        A  B  C  D  E  F */
    /* A */ { 0, 4, 2, 0, 0, 0 },
    /* B */ { 4, 0, 1, 5, 0, 0 },
    /* C */ { 2, 1, 0, 8, 10, 0 },
    /* D */ { 0, 5, 8, 0, 2, 6 },
    /* E */ { 0, 0, 10, 2, 0, 3 },
    /* F */ { 0, 0, 0, 6, 3, 0 },
};

void print_path(const int prev[], int v) {
    if (prev[v] != -1) print_path(prev, prev[v]);
    printf("%c ", 'A' + v);
}

int main(void) {
    int dist[V], done[V], prev[V];
    for (int i = 0; i < V; i++) { dist[i] = INF; done[i] = 0; prev[i] = -1; }
    dist[0] = 0;                                  /* start at A */

    for (int step = 0; step < V; step++) {
        int u = -1;
        for (int i = 0; i < V; i++)               /* closest unfinished vertex */
            if (!done[i] && dist[i] != INF && (u == -1 || dist[i] < dist[u])) u = i;
        if (u == -1) break;
        done[u] = 1;
        for (int v = 0; v < V; v++) {             /* relax its edges */
            if (graph[u][v] && !done[v] && dist[u] + graph[u][v] < dist[v]) {
                dist[v] = dist[u] + graph[u][v];
                prev[v] = u;
            }
        }
    }

    for (int v = 0; v < V; v++) {
        printf("A to %c: distance %2d, path ", 'A' + v, dist[v]);
        print_path(prev, v);
        printf("\n");
    }
    return 0;
}

Output

A to A: distance  0, path A 
A to B: distance  3, path A C B 
A to C: distance  2, path A C 
A to D: distance  8, path A C B D 
A to E: distance 10, path A C B D E 
A to F: distance 13, path A C B D E F
  • The direct road from A to B has length 4, yet the shortest route is A → C → B with length 3. Dijkstra finds it because it settles C (distance 2) first and then relaxes the edge C–B.
  • The prev array stores each vertex’s predecessor on its best route. print_path follows it backwards recursively, printing from the start, to show the full route.
  • Checking dist[i] != INF prevents the integer overflow that INF + weight would cause, and it means unreachable vertices are never chosen.

Complexity

ImplementationTimeBest for
Array scan (this lesson)O(V²)Small or dense graphs
Binary heap priority queue + adjacency listO((V + E) log V)Large, sparse graphs such as road maps

With a heap, the “find the closest unfinished vertex” step becomes a pop from a priority queue instead of a scan of every vertex.

Limitations

  • Negative edge weights break the greedy reasoning: a vertex could be finished too early and later become reachable more cheaply. Use the Bellman–Ford algorithm for graphs with negative weights; it can also detect negative cycles.
  • For unweighted graphs, plain BFS gives the same answer more simply.
  • For shortest paths between every pair of vertices in a small graph, Floyd–Warshall is often simpler.

Common Mistakes

  1. Using it with negative weights.
  2. Overflow when adding a weight to an “infinite” distance.
  3. Treating 0 as “no edge” in a graph that has real zero-length edges; use a separate marker in that case.
  4. Not recording predecessors, leaving you with distances but no routes.

Practice Exercises

Exercise 1. In the example, why is the route to E 10 (via D) rather than the direct road from C, also 10 long?

Show answer

Through C the total is 2 + 10 = 12. Through B and D it is 3 + 5 + 2 = 10, so the longer-looking route is actually shorter.

Exercise 2. Change the code so it stops early once a chosen target vertex is finished.

Show answer

After done[u] = 1; add if (u == target) break;. A vertex’s distance is final as soon as it is finished, so nothing later can improve it.

Frequently Asked Questions

Do map apps use Dijkstra’s algorithm?

They build on it. Real systems use faster variants such as A* search, which adds a distance estimate towards the target, and heavy precomputation to answer queries on huge road networks quickly.

Does Dijkstra work on directed graphs?

Yes. Store one-way roads in only one direction of the matrix or list; the algorithm itself does not change.

Summary

  • Dijkstra finds single-source shortest paths with non-negative weights.
  • Repeatedly finish the closest vertex and relax its edges.
  • O(V²) with an array; O((V + E) log V) with a heap.
  • Keep a predecessor array to rebuild routes; use Bellman–Ford for negative weights.

Next: Dynamic Programming in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *