Primero, el cuestionario del capítulo 5Primero, repasa el capítulo 5
Haz el cuestionario del capítulo 5: 10 preguntas, se aprueba con 7 correctas. Puedes repetirlo cuantas veces quieras.
Graphs at Work
Capítulo 6, lección 2 de 2
Real problems, turned into graphs and solved with the right tool from this course.
Narrado en inglés. Activa arriba los subtítulos en inglés, árabe, alemán, español o francés.
Lección escrita
10 min de lecturaEscrita en inglés.
About twelve hundred years ago, a collection of puzzles called Problems to Sharpen the Young was copied in medieval Europe. It is linked to Alcuin of York, a scholar at the court of Charlemagne. One puzzle asks a farmer to ferry a wolf, a goat and a cabbage across a river, in a boat that holds only him and one of them. Left alone, the wolf eats the goat, and the goat eats the cabbage.
It looks like a riddle about animals. In fact it is a shortest path problem, on a graph that nobody drew for a thousand years. Every lesson of this course handed you a graph; real problems never do. Finding the graph is the real skill. This final lesson covers four real problems, how to turn each one into a graph, how to choose the right tool from the course, and a map of everything you have learned.
Across the river
Step one is always the same question: what are the things, and what connects them? Here a thing is a situation: who is on which bank.
- Vertices. The farmer, the wolf, the goat and the cabbage are each on the left bank or the right bank, so there are 2 × 2 × 2 × 2 = 16 situations. Six of them leave something in danger (the wolf with the goat, or the goat with the cabbage, without the farmer). That leaves 10 safe situations: our vertices.
- Edges. Two situations are joined when one boat trip turns one into the other: the farmer crosses alone, or with one passenger. Ten vertices, and ten edges.
- Question. Now the puzzle is a question from lesson 6: the shortest path from everyone on the left to everyone on the right. Breadth-first search answers it: seven crossings.
The ten safe situations and the boat trips between them.
The search also finds that there are exactly two solutions, and that both must start the same way: the goat goes first. (Take the wolf, and the goat eats the cabbage; take the cabbage, and the wolf eats the goat.)
Drawn out, the whole puzzle is a single line with one diamond in the middle. The two solutions are simply the two sides of that diamond: after bringing the goat across and returning, take the wolf across next, or take the cabbage.
The two solutions are the two sides of the diamond.
This is the recipe for the whole lesson:
from collections import deque
ITEMS = "FWGC" # farmer, wolf, goat, cabbage; a situation = the set on the right bank
def safe(right):
for pair in ("WG", "GC"): # wolf with goat, goat with cabbage
together = (pair[0] in right) == (pair[1] in right)
if together and ((pair[0] in right) != ("F" in right)):
return False
return True
def moves(right):
side = "F" in right # the farmer's bank: True = right
for passenger in [None] + [x for x in "WGC" if (x in right) == side]:
new = set(right) ^ {"F"} ^ ({passenger} if passenger else set())
if safe(new):
yield frozenset(new)
def crossings():
start, goal = frozenset(), frozenset(ITEMS)
dist = {start: 0}
queue = deque([start])
while queue:
u = queue.popleft()
for v in moves(u):
if v not in dist:
dist[v] = dist[u] + 1
queue.append(v)
return dist[goal], len(dist)
crossings() # (7, 10): seven crossings, ten safe situations reached
Word ladders
On Christmas Day in 1877, Lewis Carroll invented a word game. Two years later, from 29 March 1879, he published it in Vanity Fair under the name Doublets. Change one letter at a time, and every step must be a real word. Carroll's own example turns HEAD into TAIL:
Here the graph is never drawn at all. Every word is a vertex, and two words are joined when they differ in exactly one letter. The question is again a shortest path.
In the lesson's small list of fourteen words (HEAD, HEAL, HEAT, HELD, HELL, HALL, HAIL, TAIL, TALL, TELL, TEAL, TEAR, TOLL, TALE), breadth-first search finds that five steps is the minimum, and that there are seven different ladders of that length. Carroll's is one of them.
Fourteen words, nineteen one-letter edges, and Carroll's ladder.
Search from both ends. A useful trick for big graphs like this one is to search from both ends at once, and stop when the two searches meet. Here, the words two steps from HEAD touch the words two steps from TAIL, so 2 + 1 + 2 = 5. Each side only goes half as deep, and since the number of words reached grows quickly with depth, that can save an enormous amount of work.
At a larger scale, Donald Knuth built this graph for 5,757 common five-letter words. 671 of them are joined to no other word at all, including the word aloof. So a graph can be too big to store and still easy to search, because you only need the neighbours of the word in front of you: try each position and each letter, and keep the real words.
from collections import deque
WORDS = {"HEAD", "HEAL", "HEAT", "HELD", "HELL", "HALL", "HAIL", "TAIL",
"TALL", "TELL", "TEAL", "TEAR", "TOLL", "TALE"}
def neighbours(word): # generated on demand: the graph is never stored
for i in range(len(word)):
for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
w = word[:i] + c + word[i + 1:]
if w != word and w in WORDS:
yield w
def ladder(start, goal):
prev = {start: None}
queue = deque([start])
while queue:
u = queue.popleft()
if u == goal:
path = []
while u:
path.append(u)
u = prev[u]
return path[::-1]
for v in neighbours(u):
if v not in prev:
prev[v] = u
queue.append(v)
len(ladder("HEAD", "TAIL")) - 1 # 5 steps
Choosing projects
A small studio can take three projects: an online shop that pays 9 (thousand dollars), a mobile app that pays 7, and an annual report that pays 4. Each needs resources that cost money:
| Project | Pays | Needs |
|---|---|---|
| Online shop | 9 | Server, Designer |
| Mobile app | 7 | Server, Developer |
| Annual report | 4 | Designer |
| Resource | Server | Designer | Developer |
|---|---|---|---|
| Costs | 4 | 3 | 8 |
Which projects should the studio take? Trying every choice works for three projects (8 plans), but not for three hundred (2³⁰⁰, about 2 × 10⁹⁰ plans).
The trick, from 1970 (the closure problem, introduced by Rhys and Balinski and solved by a minimum cut). Build a flow network:
- a pipe from the source to each project, with its payment;
- a pipe from each resource to the sink, with its cost;
- a pipe with no limit from each project to every resource it needs.
Payments in, costs out, and unlimited pipes in between.
Every cut now describes a plan. Projects left on the source side are taken, and the resources they need must come along, because a pipe with no limit can never be cut.
The minimum cut here is 14: the app's payment (7), plus the server (4), plus the designer (3). The best profit is the total of the payments, 20, minus the cut: 6 thousand dollars. Take the shop and the report, and skip the app.
Why the cut gives the profit. A cut pays the payments of the projects you skip, plus the costs of the resources you buy. The total of the payments minus that cut is exactly your profit (payments taken minus costs paid). So the smallest cut is the biggest profit.
The minimum cut: skip the app, buy the server and the designer.
The app pays well, but its developer costs even more. Mining companies use the same cut to decide which blocks of an open-pit mine are worth digging: a block can only be dug once the blocks above it are gone.
How many can fail?
On the sketch map of the Netherlands from lesson 10, how many roads must close before Amsterdam is cut off from Zwolle?
Give every road a capacity of one, in both directions, and compute the maximum flow. Each unit of flow is a route, and no two routes share a road. The flow is three:
- Amsterdam, Amersfoort, Zwolle;
- Amsterdam, Utrecht, Arnhem, Apeldoorn, Zwolle;
- Amsterdam, Leeuwarden, Zwolle.
And the minimum cut is three roads: Amersfoort to Zwolle, Apeldoorn to Zwolle, and Amsterdam to Leeuwarden. Close those three, and Zwolle and the whole north are unreachable from Amsterdam. Notice that the cut is not simply the roads around one city: Amsterdam and Zwolle each have four roads.
Three routes that share no road, and a cut of three roads.
Karl Menger, whom we met in the salesman lesson, proved it long before maximum flow existed; today it is max flow = min cut with every capacity equal to one.
A second version counts towns instead of roads. Split each town into an entrance and an exit, joined by a pipe of capacity one, and the same maximum flow counts the routes that share no town. Network engineers ask this question about cables and routers every day: how many failures can we survive?
Choosing the tool
With the graph in hand, the question tells you the tool. Here is the whole course on one page:
| Question | Tool | Lesson |
|---|---|---|
| Fewest steps | Breadth-first search | 6 |
| Cheapest route with weights | Dijkstra | 10 |
| Weights can be negative | Bellman-Ford | 11 |
| Every pair at once | Floyd-Warshall | 12 |
| One route, with a good guess | A* | 13 |
| Connect everything cheaply | Minimum spanning tree | 15 |
| Groups that only grow | Union-find | 14 |
| Tasks with dependencies | Topological sort | 8 |
| One-way streets and cycles | Strongly connected components | 9 |
| Conflicts that must not share a slot | Colouring | 16 |
| Pairs across two sides | Matching | 18 |
| Capacities and bottlenecks | Maximum flow, minimum cut | 19 |
When the question is to visit every place, or to use the fewest colours, remember lesson 17: no fast exact method is known, so use a good heuristic, and measure it against a bound.
One more check before you run anything: size. A method that takes V³ steps is instant for a hundred vertices (10⁶ steps) and hopeless for ten million (10²¹).
The whole course on one page.
Twenty lessons
We started with seven bridges in Königsberg, and a handshake. Since then you have explored graphs with breadth-first and depth-first search, found shortest paths four different ways, connected networks cheaply, faced problems nobody can solve quickly, and pushed flow through pipes.
Twenty lessons in six chapters.
Each chapter ends with a quiz on the platform. Pass them all, and you can earn a certificate that anyone can verify online. But the best practice is your own problem: find the things, find the links, ask the question, and let the graph do the work.
Key ideas
- Every modelling job starts with three choices: the vertices, the edges and the question.
- Vertices can be situations or words, not just places. Edges can be moves, one-letter changes or pipes with no limit.
- Flows and cuts reach far beyond pipes: choosing projects, and counting the failures a network can survive.
- The question picks the tool, as long as you check the size of the graph first.
Check yourself
1. In the river puzzle, why is there only one possible first move?
2. In the studio example, the developer's cost drops from 8 to 2. What is the best plan now?
3. You must assign exam slots so that no student has two exams at once. Which tool from the course fits, and what are the vertices and edges?
Practice on the platform
On learngraphtheory.org, every algorithm in this course has its own guide and visualizer, and the practice editor lets you write the code yourself. In the Dijkstra visualizer, import the fourteen words, give every step a weight of one, and run it from HEAD to TAIL: it finds HEAD, HEAL, HELL, HALL, HAIL, TAIL, five steps, a ladder as short as Carroll's.
A continuación