Transcript
A maze, a road map, a web of friends: underneath, they're all the same thing, points joined by lines. There are two classic ways to walk through one: spread out like a ripple, or dive down one path until it ends. Today: graphs.
A graph is just vertices, the points, and edges, the lines between them. This one has seven vertices and eight edges. An edge can have a direction, like a one-way street, or a weight, like the minutes a road takes.
To store it, one way is a big table: a row and a column for every vertex, with a one wherever two are joined. The other way: each vertex keeps a short list of its neighbors. For a road map with a million junctions, the table would need a trillion cells, but the lists only about three million entries.
Now the maze as a graph. Breadth-first search starts at the entrance and spreads out, one ring at a time. It uses a queue from episode three: take the cell at the front, and add its unvisited neighbors to the back. So the first time it reaches the exit, it has found the shortest route: eleven steps.
Depth-first search picks one way and keeps going, deeper and deeper. At a dead end, it backs up to the last place with a way it hasn't tried. That's a stack, like the undo button from episode three. It finds the exit too, but by a route of twenty-one steps instead of eleven.
Race them on the same maze: here the dive gets lucky and reaches the exit after twenty-nine cells, while the ripple checks thirty-four. But only the ripple promises the fewest steps. The dive is great for exploring every corner, or for checking whether a way out exists at all.
Points and lines, stored as a table or as lists, explored as a ripple with a queue, or a dive with a stack. Next time: when every road has a length, how does a map app find the fastest route? See you there.
Next episode: when every road has a length, how does a map app find the fastest route?