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)
Reference
Cheat Sheet
Keep these facts handy while you work with Dijkstra's Algorithm in C in C.
After settling 0, vertex 2 is closest (1). Settling it improves vertex 1 from 4 to 3.
Settling 1 improves vertex 3 from 6 to 4.
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.
Remember
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.