Dijkstra in C: solved exercise
Dijkstra in C: solved exercise
If you searched for a solved Dijkstra algorithm exercise in C, here is the classic adjacency-matrix implementation: it finds the shortest path from a source node to all other nodes in a directed, weighted graph with non-negative weights.
The matrix implementation is O(Vยฒ), suitable for dense or small graphs. For large sparse graphs, a priority queue (min-heap) gives O((V + E) log V).
Problem statement
Given a 5-node graph (0โ4) with the following edges:
Find the minimum distances from node 0 to all other nodes using Dijkstra.
C solution
Expected output
Common mistakes
- Using negative weights: Dijkstra does not work correctly with negative-weight edges. Use Bellman-Ford for that case.
- Not initializing all distances to INF before starting: uninitialized distances produce incorrect paths.
- Adding
INF + weightwithout checking thatdist[u] != INF: causes integer overflow. - Confusing directed and undirected graphs in the matrix: for undirected graphs,
graph[u][v] == graph[v][u].
Practical use
Dijkstra is the standard algorithm for GPS navigation, network routing (OSPF), strategy games (pathfinding on maps), and any shortest-path problem with non-negative weights. The priority-queue version is what is used in production for large graphs.
Recommended next exercise
- Binary search in C: solved exercise
- Euclidean algorithm (GCD) in C: solved exercise
- Merge sort in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why does Dijkstra not work with negative weights?
Because the algorithm assumes that once a node is marked as visited, its distance is already the minimum possible. With negative weights, a shorter path might arrive at that node later, violating that assumption. Bellman-Ford handles negative weights in O(VยทE).
When should I use the priority queue version versus the matrix version?
The priority-queue version (min-heap) is O((V + E) log V) and is preferred for sparse graphs where E « Vยฒ. The matrix version is O(Vยฒ), simpler to implement, and acceptable when V is small (< 1000) or the graph is dense.
How do I reconstruct the path, not just the distance?
Add a predecessor[V] array initialized to -1. When an edge is relaxed and dist[v] is updated, store predecessor[v] = u. At the end, trace the predecessor array from the destination back to the source to recover the route.