Topics / Data Structures & Algorithms / Q22
Implement Dijkstra's shortest-path algorithm in C.
Short answer: Repeatedly select the unvisited vertex with the smallest known distance, then relax its outgoing edges. Requires nonnegative weights.
#include <stdbool.h>
#include <stdint.h>
#define N 8
/* -1 = no edge; other weights must be nonnegative. */
void dijkstra(const int32_t g[N][N], int src,
int64_t d[N])
{
bool done[N] = {0};
for (int i = 0; i < N; i++) d[i] = INT64_MAX;
d[src] = 0;
for (int k = 0; k < N; k++) {
int u = -1;
for (int i = 0; i < N; i++)
if (!done[i] && (u < 0 || d[i] < d[u]))
u = i;
if (u < 0 || d[u] == INT64_MAX) break;
done[u] = true;
for (int v = 0; v < N; v++)
if (!done[v] && g[u][v] >= 0 &&
d[u] + g[u][v] < d[v])
d[v] = d[u] + g[u][v];
}
}
If 0→1 costs 2, 1→2 costs 3 and 0→2 costs 9, the best cost to 2 is 5. INT64_MAX represents unreachable vertices. With this fixed N and int32_t weights, distance additions fit in int64_t. Time O(N²), space O(N); a min-heap improves performance on sparse graphs.