C Weighted Graphs

Intermediate
6 min read
Updated: Nov 2026
1 example

Edges with Costs

In a weighted graph each edge carries a number: distance, time, cost, or capacity. A matrix stores the weight instead of 1, with 0 or a large sentinel meaning "no edge". The cost of a path is the sum of its edge weights, and many algorithms (Dijkstra, Prim, Kruskal) find paths or trees of minimum total weight.

Remember
int w[3][3] = {{0, 4, 10},
                {4, 0, 3},
                {10, 3, 0}};   /* 0 = no edge */

Cheat Sheet

Keep these facts handy while you work with Weighted Graphs in C.

TopicDetail
WeightCost on an edge
Path costSum of weights
No edge0 or INF sentinel
UsesMaps, networks, scheduling

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Adjacency Matrix.

Example 1 — Compare two routes

Go from 0 to 2 directly or through 1.

C
#include <stdio.h>

int main(void) {
    int w[3][3] = {
        {0, 4, 10},
        {4, 0, 3},
        {10, 3, 0}
    };
    int path[] = {0, 1, 2};
    int cost = 0;

    for (int i = 0; i + 1 < 3; i++) cost += w[path[i]][path[i + 1]];

    printf("path 0-1-2 costs %d\n", cost);
    printf("direct 0-2 costs %d\n", w[0][2]);
    return 0;
}

How It Works

  1. The two-edge route costs 4 + 3 = 7.
  2. The direct edge costs 10.
  3. The longer route in hops is the cheaper route in cost.

Edge Cases & Pitfalls

Check these before relying on Weighted Graphs in real programs.

zero

Zero as a real weight

If an edge can have weight 0, use INF or -1 for "no edge".

neg

Negative weights

Dijkstra's algorithm requires non-negative weights.

Key Takeaways

  • Weights replace 1s.
  • Path cost = sum.
  • Fewest edges is not cheapest.

One line: In a weighted graph each edge carries a number: distance, time, cost, or capacity.

Frequently Asked Questions

A graph in which each edge has an associated numeric value such as distance or cost.
In a matrix, store the weight in m[u][v]; in an adjacency list, add a weight field to each edge node.
Continue with "C Adjacency Matrix" next. Store a graph in a 2D array with O(1) edge checks. The C Graphs hub lists every topic in order.

Next: Adjacency Matrix

Store a graph in a 2D array with O(1) edge checks.

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.

10 people found this page helpful