Dijkstra's Algorithm in C

Advanced
6 min read
Updated: Nov 2026
1 example

Cheapest Paths with Non-Negative Weights

Dijkstra's algorithm finds the cheapest path from a source to every vertex when all weights are non-negative. Keep a dist array (infinity except the source = 0). Repeatedly pick the unsettled vertex with the smallest distance, mark it settled, and relax its edges. With a matrix and linear scan it is O(V^2); with a binary heap and adjacency lists, O((V + E) log V).

Remember
dist[src] = 0
repeat V times:
    u = unsettled vertex with smallest dist
    settle u
    for each neighbor v: relax(u, v)

Cheat Sheet

Keep these facts handy while you work with Dijkstra's Algorithm in C in C.

TopicDetail
WeightsNon-negative only
Matrix versionO(V^2)
Heap versionO((V + E) log V)
GreedySettled distances never change

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Minimum Spanning Trees in C.

Example 1 — Shortest paths from vertex 0

Five vertices; edges 0-1:4, 0-2:1, 2-1:2, 1-3:1, 2-3:5, 3-4:3.

C
#include <stdio.h>
#define V 5
#define INF 1000000

int main(void) {
    int w[V][V] = {{0}};
    int e[][3] = {{0, 1, 4}, {0, 2, 1}, {2, 1, 2}, {1, 3, 1}, {2, 3, 5}, {3, 4, 3}};
    for (int i = 0; i < 6; i++) {
        w[e[i][0]][e[i][1]] = e[i][2];
        w[e[i][1]][e[i][0]] = e[i][2];
    }

    int dist[V], parent[V], done[V] = {0};
    for (int i = 0; i < V; i++) { dist[i] = INF; parent[i] = -1; }
    dist[0] = 0;

    for (int round = 0; round < V; round++) {
        int u = -1;
        for (int i = 0; i < V; i++)
            if (!done[i] && (u < 0 || dist[i] < dist[u])) u = i;
        done[u] = 1;
        printf("settle %d (dist %d)\n", u, dist[u]);
        for (int v = 0; v < V; v++)
            if (w[u][v] && !done[v] && dist[u] + w[u][v] < dist[v]) {
                dist[v] = dist[u] + w[u][v];
                parent[v] = u;
            }
    }

    int path[V], len = 0;
    for (int v = 4; v != -1; v = parent[v]) path[len++] = v;
    printf("path to 4:");
    for (int i = len - 1; i >= 0; i--) printf(" %d", path[i]);
    printf("\n");
    return 0;
}

How It Works

  1. After settling 0, vertex 2 is closest (1). Settling it improves vertex 1 from 4 to 3.
  2. Settling 1 improves vertex 3 from 6 to 4.
  3. The final distances are 0, 3, 1, 4, 7 and the parents give the path 0, 2, 1, 3, 4.

Edge Cases & Pitfalls

Check these before relying on Dijkstra's Algorithm in C in real programs.

neg

Negative weights

A settled vertex could later be improved, breaking the algorithm.

inf

Adding to INF

Use a moderate INF constant and guard additions to avoid overflow.

Key Takeaways

  • Pick the closest unsettled vertex.
  • Relax its edges.
  • Non-negative weights only.

One line: Dijkstra's algorithm finds the cheapest path from a source to every vertex when all weights are non-negative.

Frequently Asked Questions

It repeatedly settles the unsettled vertex with the smallest known distance and relaxes the edges leaving it.
O(V^2) with an adjacency matrix and linear scan, or O((V + E) log V) with a binary heap.
Continue with "Minimum Spanning Trees in C" next. Understand spanning trees by enumerating them on a small graph. The C Graph Algorithms hub lists every topic in order.

Next: Minimum Spanning Trees in C

Understand spanning trees by enumerating them on a small graph.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful