Shortest Path Basics in C

Advanced
8 min read
Updated: Nov 2026
2 examples

Fewest Edges and Relaxation

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;
}

Cheat Sheet

Keep these facts handy while you work with Shortest Path Basics in C in C.

TopicDetail
UnweightedBFS + parent array
WeightedRelaxation
Rebuild pathFollow parent links back
Negative edgesDijkstra fails; use Bellman-Ford

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Dijkstra's Algorithm in C.

Example 1 — Shortest path by hops

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;
}

How It Works

  1. BFS records which vertex discovered each other vertex.
  2. Starting at 5 and following parents gives 5, 2, 3, 0.
  3. 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;
}

How It Works

  1. The known cost to reach vertex 2 is 10.
  2. Going through vertex 1 costs 4 + 3 = 7, which is cheaper.
  3. 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.

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.

Next: Dijkstra's Algorithm in C

Compute shortest weighted paths from one source with an adjacency matrix.

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.

11 people found this page helpful