Weights and direction
After this: Read a graph with weights and one-way edges, and work out the cost of a path by hand.
On this page · 9 sections · 3 checks
A map app does not count the roads between you and the café. It adds up their lengths. And some of those roads are one-way. The graphs tutorial showed arrows for one-way connections, but its edges had no numbers on them. This lesson adds the numbers, and then uses arrows on every road.
Here is a reminder of the words. A graph is a set of things and the connections between them. Each thing is a , and each connection is an . On a map, a node is a place and an edge is a road.
Three places and three roads
Here is the smallest map that shows the problem. You are at Home and you want to reach the Café. The number on each road is its length in kilometres.
There are two ways to go.
| Route | Roads used | Total length |
|---|---|---|
| Home to Café, directly | 1 | 4 km |
| Home to Park, then Park to Café | 2 | 1 + 2 = 3 km |
If you count roads, the direct route wins, because 1 is less than 2. If you add up lengths, the route through the park wins, because 3 is less than 4. The direct road goes round a hill, so it is long.
So the route with the fewest roads is not always the shortest. To find the shortest route, the graph must hold more than its connections. It must hold a number for each road.
A number on every edge
The number on an edge is called its . It can be a distance, a price or a time. A graph with a weight on every edge is called a .
The cost of a path
A is a list of edges that you follow one after another. The is what you get when you add up its weights. It is not the number of edges. The path Home → Park → Café has two edges, and its cost is 1 + 2 = 3.
Edges with a direction
Some streets are one-way. You can drive along them in one direction but not in the other. A graph can show this too. In a , every edge goes one way, and we draw it as an arrow. The edge A→B lets you go from A to B. It does not let you go from B to A. If both directions are allowed, the graph has two edges, one for each direction.
From here on we use letters, and we make every road one-way. A is Home, B is the Café, and C is the Park.
This graph has three edges: A→B with weight 4, A→C with weight 1, and C→B with weight 2.
Writing it in code
The graphs tutorial stored a graph as an adjacency list: a dictMap that gives each node a list of its neighbours. For a weighted graph, we make one change. Each neighbour now comes with its weight.
graph = { "A": [("B", 4), ("C", 1)], # A -> B costs 4, A -> C costs 1 "B": [], # no outgoing edges, but B still needs a key "C": [("B", 2)], # C -> B costs 2}for next_node, weight in graph["A"]: print("A ->", next_node, "costs", weight)A -> B costs 4 A -> C costs 1
record Edge(String to, int weight) {} // one outgoing edge: where it goes and what it costs
Map<String, List<Edge>> graph = new LinkedHashMap<>(); // keeps insertion order, like a dictgraph.put("A", List.of(new Edge("B", 4), new Edge("C", 1))); // A -> B costs 4, A -> C costs 1graph.put("B", List.of()); // no outgoing edges, but B still needs a keygraph.put("C", List.of(new Edge("B", 2))); // C -> B costs 2for (Edge e : graph.get("A")) System.out.println("A -> " + e.to() + " costs " + e.weight());A -> B costs 4 A -> C costs 1
Here is how to read it.
Ahas two outgoing edges: one toBwith weight 4, and one toCwith weight 1.- An edge is stored only under the node it leaves. A→C is stored under
A, not underC. Bhas no outgoing edges, but it still needs a key. Without that key, looking upBwould fail.
The graph for the rest of this tutorial
Now we add two more nodes, D and E. This table shows all the edges. You have already met the first three.
| Edge | Weight |
|---|---|
| A→B | 4 |
| A→C | 1 |
| C→B | 2 |
| B→D | 1 |
| C→D | 5 |
| D→E | 3 |
That makes five nodes and six one-way edges. No edge points at A, and no edge leaves E.
Two paths from A to E show why cost matters.
- A → B → D → E has three edges and costs 4 + 1 + 3 = 8.
- A → C → D → E also has three edges and costs 1 + 5 + 3 = 9.
The two paths have the same number of edges but different costs. The next lesson looks at what this means for a search.
In code, the graph has the same shape as before, with more rows. The last lines print the edges that leave C, then count the edges that leave E.
graph = { "A": [("B", 4), ("C", 1)], # A -> B costs 4, A -> C costs 1 "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": [("E", 3)], "E": [], # no outgoing edges, but E still needs a key}for next_node, weight in graph["C"]: print("C ->", next_node, "costs", weight)print("edges out of E:", len(graph["E"]))C -> B costs 2 C -> D costs 5 edges out of E: 0
record Edge(String to, int weight) {} // one outgoing edge: where it goes and what it costs
Map<String, List<Edge>> graph = new LinkedHashMap<>(); // keeps insertion order, like a dictgraph.put("A", List.of(new Edge("B", 4), new Edge("C", 1))); // A -> B costs 4, A -> C costs 1graph.put("B", List.of(new Edge("D", 1)));graph.put("C", List.of(new Edge("B", 2), new Edge("D", 5)));graph.put("D", List.of(new Edge("E", 3)));graph.put("E", List.of()); // no outgoing edges, but E still needs a keyfor (Edge e : graph.get("C")) System.out.println("C -> " + e.to() + " costs " + e.weight());System.out.println("edges out of E: " + graph.get("E").size());C -> B costs 2 C -> D costs 5 edges out of E: 0
Watch it happen
First we look at direction. The button says BFS. That is the walk from the graphs tutorial, and the next lesson says more about it. For now, watch which nodes it reaches. Run it from E, then from C.
- BFS from EStart at E. The only edge that touches E is D→E, and it points into E. Watch how far BFS gets.
- BFS from C
Pick a start node and run an algorithm.
Check yourself
What does the path A → B → D → E cost?
The graph has the edge A→B with weight 4. Can you travel from B to A?
What does this print?
graph = { "A": [("B", 4), ("C", 1)], # A -> B costs 4, A -> C costs 1 "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": [("E", 3)], "E": [], # no outgoing edges, but E still needs a key}for next_node, weight in graph["C"]: print("C ->", next_node, "costs", weight)print("edges out of E:", len(graph["E"]))record Edge(String to, int weight) {} // one outgoing edge: where it goes and what it costs
Map<String, List<Edge>> graph = new LinkedHashMap<>(); // keeps insertion order, like a dictgraph.put("A", List.of(new Edge("B", 4), new Edge("C", 1))); // A -> B costs 4, A -> C costs 1graph.put("B", List.of(new Edge("D", 1)));graph.put("C", List.of(new Edge("B", 2), new Edge("D", 5)));graph.put("D", List.of(new Edge("E", 3)));graph.put("E", List.of()); // no outgoing edges, but E still needs a keyfor (Edge e : graph.get("C")) System.out.println("C -> " + e.to() + " costs " + e.weight());System.out.println("edges out of E: " + graph.get("E").size());Connect
- Say what an edge weight is, and what a one-way edge does not allow.
- Show on three nodes why the route with the fewest edges is not always the shortest: one edge costing 4 against two edges costing 3.
- Store a weighted directed graph as node → (neighbour, weight) pairs, with a key for every node.
- Work out the cost of a path by adding its edge weights: A → B → D → E costs 4 + 1 + 3 = 8.