Weighted/unweighted graphs
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
In an unweighted graph every link counts the same, so the best path is the one with the fewest steps. In a weighted graph each link carries a number, such as distance, time or price, and the best path is the one with the smallest total.
Practical use cases
- Web app: Fastest route versus fewest turns. A delivery app finds a route from kitchen to customer. Counting road segments finds the route with the fewest turns, but one segment may be a jammed highway. Giving each road a travel time as its weight lets the app pick the route that is actually quickest.
- Web app: Cheapest flight combination. A travel site lets you pick the cheapest way from Delhi to Kochi with a stop. Each flight is an edge weighted by its price, so adding up the weights finds the lowest total. Choosing the fewest stops would often cost more. The weight turns a vague best into a number you can compare.
- System: Internet routing and game maps. Network routers pick paths using costs such as delay, and game maps give mud, roads and water different movement costs. In both cases the numbers on the lines change which path is best. Change one weight and the best route can flip completely.
The story: Three Rickshaws and a Cheaper Way
Kabir needed to go from home (A) to the cricket ground (D). Mira drew the roads and said, "Just count the roads! The route with the fewest roads wins." Two routes had only two roads each. Easy.
But Kabir had only a few coins. He asked the rickshaw uncle about fares. The uncle said, "Short lane, long lane, it is not the same. Some roads are costly because of traffic." Mira wrote a number on every road: its fare in rupees.
Now the two-road routes both cost ₹9. Then Kabir noticed a sneaky route: three small cheap roads, costing 1, then 1, then 5, only ₹7. More roads, less money!
That number on a road is called its weight. A graph without such numbers is unweighted, where every road is equal. A graph with them is weighted, and "best path" now means the smallest total weight.
How to spot this problem, and where you need it
Counting steps does not give the right answer, because some connections are longer, slower or costlier than others and you need the best total, not the shortest hop count.
Signs you need it
- Your route shows fewest stops, but users complain that it is slower or more expensive than another route.
- Each link in the data has a number attached: distance, minutes, rupees, bandwidth.
- The task says "minimum cost", "shortest distance" or "cheapest path", rather than "fewest edges".
Where to use it in a project
- Navigation, delivery routing and ETA calculation using road distances or travel times.
- Price-based planners, such as cheapest multi-leg travel, or networks choosing a low-delay path.
The solution
Store a number with each line. If all numbers are equal (or missing), a simple level-by-level search finds the fewest steps. If the numbers differ and are never negative, use a shortest-path method such as Dijkstra, which always expands the cheapest total so far using a priority queue, and adds up the weights along the way.
Payoff: Before: a route with 3 turns that takes 45 minutes. After: a route with 5 turns that takes 28 minutes, picked because weights are counted.
Explain it like I am 8
Imagine a board game. In one version every step costs the same, so you just count steps. In another, some steps cost more (a muddy road costs 5 coins, a smooth one costs 1). The coins written on each road are its weight.
How it works, step by step
- Unweighted: an edge only says "connected". Cost of a path = number of edges.
- Weighted: each edge carries a number (distance, time, price, risk).
- Cost of a path = the sum of the weights of the edges along it.
- Store the weight next to the neighbour:
B => 4instead of justB. - Remember: the path with fewest edges is not always the cheapest once weights exist.
The code in four languages
PHP
<?php
// Weighted graph as adjacency list: node => [neighbour => fare]
$graph = [
'A' => ['B' => 4, 'C' => 1],
'B' => ['A' => 4, 'C' => 1, 'D' => 5],
'C' => ['A' => 1, 'B' => 1, 'D' => 8],
'D' => ['B' => 5, 'C' => 8],
];
// Cost of a path = sum of the weights of its edges.
function pathCost(array $graph, array $path): int {
$total = 0;
for ($i = 0; $i + 1 < count($path); $i++) {
$total += $graph[$path[$i]][$path[$i + 1]];
}
return $total;
}
foreach ([['A','B','D'], ['A','C','D'], ['A','C','B','D']] as $p) {
echo implode('-', $p) . ' hops=' . (count($p) - 1) . ' cost=' . pathCost($graph, $p) . "\n";
}JavaScript
// Weighted graph as adjacency list: node -> { neighbour: fare }
const graph = {
A: { B: 4, C: 1 },
B: { A: 4, C: 1, D: 5 },
C: { A: 1, B: 1, D: 8 },
D: { B: 5, C: 8 },
};
// Cost of a path = sum of the weights of its edges.
function pathCost(graph, path) {
let total = 0;
for (let i = 0; i + 1 < path.length; i++) {
total += graph[path[i]][path[i + 1]];
}
return total;
}
for (const p of [['A','B','D'], ['A','C','D'], ['A','C','B','D']]) {
console.log(p.join('-') + ' hops=' + (p.length - 1) + ' cost=' + pathCost(graph, p));
}Java
import java.util.*;
public class Main {
// Cost of a path = sum of the weights of its edges.
static int pathCost(Map<String, Map<String, Integer>> graph, List<String> path) {
int total = 0;
for (int i = 0; i + 1 < path.size(); i++) {
total += graph.get(path.get(i)).get(path.get(i + 1));
}
return total;
}
public static void main(String[] args) {
// Weighted graph as adjacency list: node -> (neighbour -> fare)
Map<String, Map<String, Integer>> graph = Map.of(
"A", Map.of("B", 4, "C", 1),
"B", Map.of("A", 4, "C", 1, "D", 5),
"C", Map.of("A", 1, "B", 1, "D", 8),
"D", Map.of("B", 5, "C", 8));
// Fewest hops is not always cheapest: compare hops and cost
List<List<String>> paths = List.of(
List.of("A", "B", "D"), List.of("A", "C", "D"), List.of("A", "C", "B", "D"));
for (List<String> p : paths) {
System.out.println(String.join("-", p) + " hops=" + (p.size() - 1) + " cost=" + pathCost(graph, p));
}
}
}Go
package main
import (
"fmt"
"strings"
)
// pathCost is the sum of the weights of the path's edges.
func pathCost(graph map[string]map[string]int, path []string) int {
total := 0
for i := 0; i+1 < len(path); i++ {
total += graph[path[i]][path[i+1]]
}
return total
}
func main() {
// Weighted graph as adjacency list: node => {neighbour: fare}
graph := map[string]map[string]int{
"A": {"B": 4, "C": 1},
"B": {"A": 4, "C": 1, "D": 5},
"C": {"A": 1, "B": 1, "D": 8},
"D": {"B": 5, "C": 8},
}
// Fewest hops is not always cheapest: compare hops and cost
paths := [][]string{{"A", "B", "D"}, {"A", "C", "D"}, {"A", "C", "B", "D"}}
for _, p := range paths {
fmt.Printf("%s hops=%d cost=%d\n", strings.Join(p, "-"), len(p)-1, pathCost(graph, p))
}
}Time: O(path length) to price one path · Extra space: O(V + E). Weights cost only one extra number per edge, but they change which algorithm you need for shortest paths.
Watch out for
- Using plain BFS on a weighted graph and trusting "fewest hops" as "cheapest".
- Forgetting to store the weight on both ends of an undirected weighted edge.
- Treating a weight of 0 as "no edge". A free road is still a road!
Quick check
- In a weighted graph, what does the cost of a path mean?
- The number of edges
- The biggest weight on it
- The sum of the edge weights
- Route X has 2 edges costing 9 in total. Route Y has 3 edges costing 7. Which is cheaper?
- Y, it has the smaller total
- X, it has fewer edges
- They are equal
- Which is an unweighted graph?
- Cities with distances on the roads
- Friends: a line means "are friends"
- Flights with prices