In an unweighted graph, BFS with a parent array finds a shortest path (fewest edges) and lets you rebuild it by walking parents backward. In a weighted graph the key operation is relaxation: if going through u to v is cheaper than the best known distance, update it (dist[v] = dist[u] + w). Dijkstra and Bellman-Ford repeat relaxations in a specific order.
Remember
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w; /* relax edge u -> v */
parent[v] = u;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Shortest Path Basics in C in C.
From 0 to 5 in a graph with edges 0-1, 0-3, 1-4, 2-3, 2-5.
C
#include <stdio.h>
#define V 6
int main(void) {
int adj[V][V] = {{0}};
int edges[][2] = {{0, 1}, {0, 3}, {1, 4}, {2, 3}, {2, 5}};
for (int i = 0; i < 5; i++) {
adj[edges[i][0]][edges[i][1]] = 1;
adj[edges[i][1]][edges[i][0]] = 1;
}
int parent[V], q[V], head = 0, tail = 0;
for (int i = 0; i < V; i++) parent[i] = -2;
parent[0] = -1;
q[tail++] = 0;
while (head < tail) {
int u = q[head++];
for (int v = 0; v < V; v++)
if (adj[u][v] && parent[v] == -2) { parent[v] = u; q[tail++] = v; }
}
int path[V], len = 0;
for (int v = 5; v != -1; v = parent[v]) path[len++] = v;
printf("shortest path 0 -> 5:");
for (int i = len - 1; i >= 0; i--) printf(" %d", path[i]);
printf(" (%d edges)\n", len - 1);
return 0;
}
Output
shortest path 0 -> 5: 0 3 2 5 (3 edges)
How It Works
BFS records which vertex discovered each other vertex.
Starting at 5 and following parents gives 5, 2, 3, 0.
Reversing that list gives the path from 0 to 5.
Example 2 — Relaxing one edge
A direct edge costs 10 but a detour costs 7.
C
#include <stdio.h>
int main(void) {
int dist[3] = {0, 4, 10}; /* best known distances from vertex 0 */
int w12 = 3; /* weight of edge 1 - 2 */
if (dist[1] + w12 < dist[2]) {
printf("relax 1-2: dist[2] %d -> %d\n", dist[2], dist[1] + w12);
dist[2] = dist[1] + w12;
}
printf("dist: %d %d %d\n", dist[0], dist[1], dist[2]);
return 0;
}
Output
relax 1-2: dist[2] 10 -> 7
dist: 0 4 7
How It Works
The known cost to reach vertex 2 is 10.
Going through vertex 1 costs 4 + 3 = 7, which is cheaper.
Relaxation lowers dist[2] to 7.
Edge Cases & Pitfalls
Check these before relying on Shortest Path Basics in C in real programs.
unwt
Using BFS on weighted graphs
BFS minimizes edges, not total weight.
neg
Negative cycles
Shortest paths are undefined when a negative cycle is reachable.
Remember
Key Takeaways
BFS for hops.
Relaxation for weights.
Parents rebuild the path.
One line: In an unweighted graph, BFS with a parent array finds a shortest path (fewest edges) and lets you rebuild it by walking parents backward.
Frequently Asked Questions
Updating the best known distance to v if a path through u is shorter.
Store a parent pointer for each vertex and walk from the target back to the source, then reverse.
Continue with "Dijkstra's Algorithm in C" next. Compute shortest weighted paths from one source with an adjacency matrix. The C Graph Algorithms hub lists every topic in order.