All episodes · From a List to Your Map App · Episode 18

Graphs: How to Store Them and Walk Through Them

Pressing play loads the video from YouTube.

A maze, a road map, a web of friends: underneath, they're all graphs, points joined by lines.
We see what vertices, edges, directions and weights are, compare two ways to store a graph (a big table, or a list of neighbors for each vertex: for a million road junctions, a trillion cells against about three million entries), then walk a maze two ways. Breadth-first search spreads like a ripple with a queue and finds the 11-step shortest route. Depth-first search dives with a stack, backs up from dead ends, and finds a 21-step route. Finally we race them on the same maze.

Every animation in this video is drawn by code, and the narration is an AI voice.

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?

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal