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 */
Reference
Cheat Sheet
Keep these facts handy while you work with Weighted Graphs in C.
Topic
Detail
Weight
Cost on an edge
Path cost
Sum of weights
No edge
0 or INF sentinel
Uses
Maps, networks, scheduling
Code
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;
}
Output
path 0-1-2 costs 7
direct 0-2 costs 10
How It Works
The two-edge route costs 4 + 3 = 7.
The direct edge costs 10.
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".