Graphs and Shortest Path
A table describes things: one row per customer, per product, per airport. Some questions are not about the things at all but about what lies between them. How do I get from Atlanta to Sydney, and with how many changes? Which pages can be reached from the home page? If this road closes, is the town cut off? None of these is a filter, a join, or a group-by. They are questions about connections, and the structure for them is a graph: a set of nodes and a set of edges between pairs of them, where an edge may have a direction and may carry a weight. Often the hardest step is the first — recognising that a word puzzle, a course catalogue, and an airline timetable are the same problem. An edge list is the natural form for a file and a poor one to ask; an adjacency list, a dictionary mapping each node to its neighbours, puts every node’s connections one lookup away, provided every node is a key.
The basic operation is a search that spreads outward from a start. Breadth-first search works in rings: everything one step away, then everything new that is two steps away. A queue produces that order by itself, and because nearer rings finish first, the first time a node is reached is by a route with the fewest steps. Three details decide whether it works: take from the front of the queue, skip what has been seen, and record a node when it joins the queue. One “came from” note per node recovers the path itself; shortest paths are not unique, and all of them are correct. The nodes a search reaches form a connected component, and looking at the components is one of the first things to do with any real network. Finally, fewest steps is not shortest distance. When edges have lengths the search must take the nearest node next, which is Dijkstra’s algorithm, and what “shortest” means becomes a modelling decision made by what is put on the edges.

Listen
| Speaker | Text |
|---|---|
| Alex | You know, um, most of the time when you and I try to organize the world, or really when anyone tries to organize their work or like just their daily life, there is this deep, almost psychological comfort in using tables, |
| Sam | right? |
| Alex | You picture a spreadsheet, you have your rows of customers, you have lists of products, uh, columns of airports with their properties neatly aligned, maybe even color coded. Yeah, |
| Sam | everybody loves a color coded spreadsheet. It feels |
| Alex | safe. It feels completely organized. But um What happens when the most important data you need isn’t the actual thing itself, but the relationship between those things? Like, what do you do when the answer you’re looking for lives entirely in the empty spaces connecting your data? |
| Sam | Well, I mean, a spreadsheet is fantastic for taking inventory. If you just need to count how many boxes are in a warehouse, you use a table, but it is fundamentally terrible at giving you directions or, you know, showing you influence, |
| Alex | which is what we actually care about a lot of the time, |
| Sam | exactly. If you want to know how a rumor travels through a high school or how a virus spreads across a continent or even just how to get from point A to point B, that rigid table structure completely breaks down. |
| Alex | It just doesn’t work, |
| Sam | no. Because you can’t put a relationship into a neat little self, |
| Alex | and that dilemma is exactly what we are tackling today. Our mission for this deep dive is to completely upgrade how you, the listener, view problem solving. We’re going to figure out how to navigate complex, messy networks, |
| Sam | and it gets messy very fast. |
| Alex | It really does. We are going to discover why the path you think is the shortest is very often an illusion masking a totally different reality. And we’ll reveal how navigating an international airline timetable and solving a newspaper word puzzle are secretly the exact same thing under the hood, |
| Sam | which is one of my favorite comparisons. |
| Alex | It’s |
| Sam | so |
| Alex | cool. |
| Sam | So, OK, let’s unpack this. When we talk about making this shift, moving away from our comfortable spreadsheets, what is the fundamental change in how we structure our thinking? |
| Alex | So the shift is moving from a list to a graph, and a graph, well, in this specific context anyway, is incredibly elegant because it consists of just two fundamental components. |
| Sam | OK, just two, right? First, you have the nodes. The nodes are the things themselves, the entities. Yeah, these could be individual people, web pages, airports, power plants, or, like you mentioned, even just words in a dictionary. |
| Alex | OK, so if we’re breaking this down into grammar, the nodes are the nouns, |
| Sam | nouns, exactly. And second, you have the edges. These are the connections, the bridges between those things. So friendships, shipping routes, hyperlinks on a blog, |
| Alex | nouns and verbs. The edges are the verbs linking them together. |
| Sam | Yeah, that’s a great way to put it. And because edges act like verbs, they behave in different ways depending on the action they describe. So they could be directed or undirected, |
| Alex | meaning what exactly? |
| Sam | Well, think about social dynamics. A mutual friendship is an undirected edge. It flows both ways equally. If you’re friends with someone, they’re friends with you. But say following a celebrity on social media or a hyperlink pointing from one website to another. That’s a directed edge. It’s a one-way arrow, |
| Alex | which totally changes how you have to navigate that network. I mean, if I can drive from Town A to Town B on a one-way highway, it doesn’t guarantee a road exists back from Town B to Town A. |
| Sam | Exactly. |
| Alex | The relationship just isn’t symmetrical. |
| Sam | The navigation changes completely. And edges also bring another layer of complexity, which is that they could be weighted or unweighted, |
| Alex | weighted meaning they have a value attached, |
| Sam | right? A connection might just simply exist like two people knowing each other. There’s no math attached to it. That’s unweighted, |
| Alex | just a simple yes or no, yes. |
| Sam | But an edge might also carry a specific cost or a number. Think about the travel time between two cities or the physical distance in miles or the price of a train ticket. That number attached to the connection is a weight. |
| Alex | OK, so that makes sense conceptually when we visualize it on a whiteboard, but um if I’m trying to actually build this in a computer, my first instinct is just to write down a massive ongoing list of who met who, an edge list. Yeah, exactly. Anna is connected to Ben. Anna is connected to Chi. She is connected to Dev. It just seems like a simple. A list of facts is the most logical, clean way to store a graph, but everything we’re looking at in the source material suggests this is a terrible way to actually ask questions about the data. Why is a simple list of edges such a trap? Well, |
| Sam | it creates a massive computational bottleneck when you start searching. Imagine you want to find out who Dev’s neighbors are. If you only have that long list of pairs, the computer has to read every single line from top to bottom, checking if Dev’s name is mentioned |
| Alex | anywhere. Oh man, it’s like having a giant shoebox completely stuffed with random receipts that just say this person meant this person. |
| Sam | That is exactly what it’s like. |
| Alex | If I want to find everyone you met at a conference, I can’t just look up your name. I literally have to read every single receipt in the entire box just in case your name is on it. |
| Sam | Which is agonizingly slow. I mean, imagine doing that for a network with 10 million connections, like a global telecommunications grid, and having to do it every single time you take a single step in your search, |
| Alex | right, that would crash immediately. |
| Sam | So what’s the fix? The alternative, the much better way to handle this is the adjacency list. This reorganizes the raw data so that each node is mapped directly to a bundle of its neighbors. OK, a bundle, yeah, you look up a node and instantly in one step, you get a complete list of everyone they’re connected to. |
| Alex | So sticking with my analogy, the adjacency list is basically a perfectly alphabetized Rolodex. Yes, |
| Sam | a Rolodex is perfect. |
| Alex | I bypassed the shoebox entirely, flip straight to your name, and right there on your card is a tidy, complete list of everyone you know. No searching required. It’s an |
| Sam | incredibly efficient structure. However, there is a critical, seemingly minor detail in setting up this Rolodex that causes one of the most common catastrophic bugs for people building these systems. Oh, what is it? When you create this index, you have to ensure that every single node gets its own dedicated blank card. Even if they don’t have any outbound connections, |
| Alex | wait, if they don’t connect outwards to anyone, like if their list of neighbors is totally empty, why do they need to take up space in the Rolodex at all? |
| Sam | Well, think back to directed edges. Imagine a node that only ever receives connections like a popular blog post that thousands of people link to, but the post itself links to absolutely nowhere. |
| Alex | Oh, OK, it’s a dead end, right? |
| Sam | It’s a target. If your search algorithm arrives at that post. And then tries to look up its neighbors to see where to go next, and that post doesn’t exist as an entry in the index. |
| Alex | The program doesn’t just politely return 0 neighbors. |
| Sam | Exactly. The computer says, I don’t know this entity at all. |
| Alex | Oh no, |
| Sam | it throws a massive error and the entire system crashes. The software essentially panics because you asked it to look up a card that physically doesn’t exist in the drawer. That makes total sense. So the golden rule of storing any graph is that every single node must have a presence in the index. Even if it’s just mapped to an empty set, |
| Alex | that is such a subtle but deadly trap. So, OK, we have our Rolodex perfectly set up. Every single node is accounted for. No empty searches, no crashes. But knowing who is connected to who in a filing cabinet isn’t the same as actually finding a path from person A to person Z. No, it’s just the foundation, right now we have to move from just storing the graph to actively searching through it, |
| Sam | which brings us to the most fundamental way to explore any network. Breadth first search. |
| Alex | I love the way this concept is usually visualized. It’s like dropping a pebble in a still pond, right? You search outward in expanding concentric rings. Yes, the |
| Sam | ripple effect. |
| Alex | First you check everyone who is exactly 1 single step away from your starting point. Then once that whole circle is checked, you expand to everyone who is 2 steps away, and so on. |
| Sam | And the engine that actually makes that outward expansion function properly is a data structure called a queue, like a line. It works exactly like a line at a grocery store checkout. Newly discovered nodes join the line at the very back, and the program only ever takes the next node to process from the very front. |
| Alex | Let me puzzle this out because the order of operations seems crucial here. If I’m writing this program and I have a line of nodes, my instinct might be to just grab the newest person I just found. |
| Sam | A lot of people do that initially, |
| Alex | but if I do that, if I mistakenly take from the back of the line instead of the front, aren’t I just going to end up sprinting down one single chain of friends forever? |
| Sam | You would completely change the nature of the algorithm. By taking from the back, you accidentally create depth first search. |
| Alex | Oh, depth first, right? |
| Sam | You look at node A, find its neighbor B, and put B at the back of the line. Then you immediately grab B, find its neighbor C, put C at the back and grab it. |
| Alex | Just going deeper and deeper. You dive |
| Sam | down a single narrow rabbit hole as far as it will possibly go. You could travel 100 steps deep before you ever bother to check the other people who were standing right next to node A at the very beginning. |
| Alex | Uh, so taking from the front of the line enforces fairness. |
| Sam | Exactly. It’s about fairness. |
| Alex | It forces the program to say, hold on, before I go deep down in this wild chain of connections. Let me finish checking every single person who is standing right here in this first ring. |
| Sam | And because nearer rings are always strictly finished before further rings are explored. Breadth-first search guarantees something crucial, which is the very first time you reach a destination node, the route you took to get there definitively has the fewest possible steps. It is mathematically impossible to find a shorter route later |
| Alex | because if there was a shorter one, you would have hit it in an earlier ring. Exactly. |
| Sam | But to make sure this grocery line doesn’t run forever, there are two other golden rules you have to implement. Oh |
| Alex | well, yeah, because if two people are mutual friends, they could just keep pointing back and forth at each other forever, right? Anna points to Ben, Ben points to Anna, and the line would just fill up with their names infinitely. That’s |
| Sam | a cycle, and it will completely freeze your program. So the first rule is skip what has already been seen. You have to maintain a separate record of who you visited so you don’t get trapped in those endless loops. Got it. And the second rule is about the timing of that record. You must record that a note has been seen the exact moment it joins the back of the queue, not when it finally reaches the front and leaves the queue. |
| Alex | Wait, why does the timing matter so much? |
| Sam | Because if you wait until they reach the front of the line to mark them as seen, they could have been added to the back of the line 50 times by 50 different mutual friends while they were waiting. |
| Alex | Oh right, so they’d just be sitting in line multiple times. |
| Sam | It would completely destroy your efficiency. You’d process the same person over and over. OK, |
| Alex | so we’ve dropped our pebble. The rings expand outward perfectly. We avoid the endless cycles. We find our target. And we know it is, say, 3 steps away, but knowing something is 3 steps away isn’t an itinerary. No, it’s just a distance, right? Like if I’m trying to book a complex flight, knowing it takes 3 layovers doesn’t tell me what actual planes to get on. How do we get the actual route out of this expanding ripple? |
| Sam | The trick is leaving a breadcrumb trail as you search. You maintain a separate dictionary that acts as a came from ledger, |
| Alex | a came from ledger, OK. |
| Sam | Every single time your search finds a new unseen node, you don’t just put it in line, you write down exactly which node introduced you to it. |
| Alex | So when node C is discovered by node B, I write in my ledger, I found C via B, and I do that for every single discovery. |
| Sam | Precisely. And then, when you finally hit your destination, you just walk backward through the ledger. You start at the target, look at your ledger to see who brought you there. Step back to that node, look at who brought them there, and repeat until you reach the starting point. Oh, that’s brilliant. Then you just reverse that list and you have your perfect step by step path from start to finish. |
| Alex | That is beautifully elegant, though it’s probably worth pointing out that this path, this optimal route with the fewest steps, is not necessarily unique, right? |
| Sam | Right. There might be 5 different routes that all take exactly 3 steps. Breadth-first search doesn’t care. It just returns the very first one it stumbles across, |
| Alex | which might just be based on the alphabet, |
| Sam | literally, yeah, it often simply depends on the arbitrary alphabetical order it checked the neighbors in. They are all mathematically equal in terms of steps. |
| Alex | OK, so breadth-first search works brilliantly if everything is connected in one giant web. But what if the ripples from our pebble hit a wall? They often do. Like, what if they just stop expanding because there is nowhere else to go? This takes us into the concept of network fragmentation. |
| Sam | Yeah, this brings up the concept of reachability. Reachability is the set of all nodes you could actually get to from a specific starting point. In the real world, networks almost never exist as one giant, perfectly connected organism. They break into pieces. |
| Alex | And these pieces have a specific name, |
| Sam | right? Yes, these isolated pieces are called connected components. |
| Alex | I want to dive into this because there’s a brilliant example we can use from the notes to illustrate this a word puzzle. Oh, the word letter puzzle. Yes, the goal of the puzzle is to change the word cold to the word warm, changing just one letter at a time, and every step in between has to be a real valid four-letter English word. |
| Sam | Most people would look at a word puzzle and think, ah, a graph theory problem. |
| Alex | I definitely didn’t. |
| Sam | But it perfectly maps to one. Every four letter word in the dictionary is a node, and an edge exists between two words if they differ by exactly one letter. |
| Alex | Like cold connecting to cord. |
| Sam | Yes, cold connects to cord, which connects to card. |
| Alex | And when you map this out using a standard dictionary, the scale of the network is wild. We’re talking 22,400 words acting as nodes and 10,600 edges connecting them into a massive web. It’s surprisingly dense, right? And it turns out using breadth-first search, the shortest path from cold to warm is just 4 steps. In fact, most words in this giant linguistic web are only 5 or 6 steps away from cold. |
| Sam | But the deeper insight comes from looking beyond just finding that path and actually examining the connected components of this word graph. The structure of the data reveals glaring |
| Alex | anomalies. What kind of anomalies? |
| Sam | Well, out of those 2400 words, there are 81 words that have absolutely zero neighbors, 000. They can’t be changed into any other word by swapping a single letter. They are entirely isolated nodes just floating in the void, |
| Alex | islands of unchangeable words. |
| Sam | That’s fascinating. But the really funny part to me is when you look at the second largest component, there’s the giant main web of thousands of connected words. But then there’s this completely isolated separate cluster floating out there all by itself. Yeah, |
| Alex | the accidental cluster. |
| Sam | Exactly. |
| Alex | It turns out it was a cluster of Roman numerals that had accidentally been left in the dictionary data file. |
| Sam | Which perfectly illustrates why analyzing components is so critical. I mean, nobody was intentionally looking for Roman numerals. The, the programmers didn’t set out to clean the data. They were just |
| Alex | trying to play a game, |
| Sam | right? But by simply asking the graph, showing the pieces that are disconnected from the main body, the error became glaringly obvious. Analyzing components isn’t just for solving word puzzles. It is an incredibly powerful diagnostic tool in data science. |
| Alex | How does finding a disconnected cluster of words translate to like a real world business case? How, how do we actually use this? |
| Sam | Consider financial fraud detection. |
| Alex | Oh, OK. |
| Sam | If you have a massive network of user accounts for an app. And you map out who sends money to whom, you’d expect a massive intertwined web. But if you suddenly find an isolated ring of 50 accounts that only trade large sums of money with each other and interact with no one else in the main network, oh wow, yeah, that isolated component is a massive red flag for a money laundering ring. |
| Alex | They expose themselves simply by being cut off from the herd. |
| Sam | Exactly. Or consider civil engineering and urban planning. If you model towns as nodes and roads as edges, you can run stress tests. If a flood knocks out a major bridge, you recalculate the graph. Do any towns suddenly become their own isolated component? Do they |
| Alex | lose |
| Sam | access, basically, right? Do they become completely cut off from the hospital node or the supply chain nodes? The lack of edges is just as informative as the edges themselves. |
| Alex | That is amazing. The empty spaces tell a whole different story. But I want to pivot here because I have to push back on something we established earlier. Oh good. We spent all this time cementing the idea that breadth-first search finds the shortest path by finding the fewest steps, but there is a classic airline routing dilemma in the source material that completely shatters this logic. |
| Sam | Ah, the unweighted versus weighted problem. Let’s hear the scenario. |
| Alex | So if you look at global flights, there is no direct flight from Atlanta to Sydney. So if I use breadth first search to find the route with the fewest flights, it gives me a two flight route from Atlanta to Sydney with a layover in Dubai. OK, 2 hops. It’s 2 steps, but geographically that route is 24,000 kilometers long. You are flying entirely across the wrong side of the planet. Not very efficient, no, because there is another two flight route going through Los Angeles that is only 15,000 kilometers. But breath-first search counts them as the exact same distance because they both take two hops. That is a massive flaw. If I’m a passenger, I don’t just care about the number of layovers. I care about the actual physical distance or the total time sitting in a seat. And |
| Sam | you’ve hit on the most important realization in graph theory. Fewest steps does not equal shortest distance, right? The moment edges have lengths or costs or time associated with them, the moment they become weighted, breadth-first search is no longer the right tool for the job. It is completely blind to those weights. |
| Alex | So how do we fix it? If the pebble in the pond doesn’t work for weighted reality, what is the right tool? |
| Sam | We use D Dyjkstra’s algorithm. It was designed to solve exactly this problem. Remember how breadth-first search uses a standard queue like a grocery line. Where it just takes whoever has been waiting the longest, right, |
| Alex | taking the oldest node from the front of the line to ensure fairness. |
| Sam | Dykstra’s algorithm swaps that standard queue for a priority queue, |
| Alex | a priority queue, |
| Sam | yeah, instead of a static line, a priority queue constantly reshuffles itself every time a new node is added or a new path to a node is found. The queue reorganizes so that it always hands you the node with the smallest total accumulated weight from the starting point. |
| Alex | OK, wait, let me process that. It always explores the physically nearest unfinished node next, regardless of how many individual steps or hops it took to get there. OK, so it’s keeping a running cumulative tally. If hop one is 500 miles and hop two is 500 miles, that’s 1000 miles total. The algorithm will prioritize that two hop route over a single direct hop, that is, say, 2000 miles long, even though the single hop has fewer edges. |
| Sam | Yes. It guarantees the smallest total weight, but this introduces a fascinating philosophical problem, one that gets to the very core of how we interact with technology, |
| Alex | which is, |
| Sam | what exactly is a weight. If you are running D Dyjkstra’s algorithm, what does shortest actually mean? |
| Alex | Well, it completely depends on what I’m measuring, right? If the weight on the edge is measuring kilometers, then shortest means physical distance. Exactly. But if the weight is driving time in minutes, then the shortest means the fastest route, which might be a geographically longer highway instead of a shorter but traffic jammed city street. And |
| Sam | if the weight is fuel consumption, shortest means most efficient. If it’s the price of a ticket, shortest means cheapest. If it’s carbon output, shortest means most environmentally friendly. Shortest is entirely a modeling decision. It’s subjective, completely. It has absolutely no intrinsic mathematical meaning until the human being programming the system decides what to put on those edges, |
| Alex | which means the algorithm is only as good as the assumptions of the person who built it. Yes, and there’s a huge trap here with modern programming tools, isn’t there? A lot of people use industry standard libraries to build these graphs because you can do it in just a few lines of code. But if you call a standard shortest path function and you forget to explicitly specify what weight to use, oh, this happens all the time. Like if you forget to tell the computer you care about kilometers or dollars or hours, the library often doesn’t throw an error, does it? |
| Sam | No, it silently defaults to assuming all edges have a weight of one. |
| Alex | So it silently reverts back to breadth first search. It just counts the hops, |
| Sam | which means if you forget that one parameter, the computer will confidently hand you that agonizing route through Dubai. |
| Alex | And you just think, well, the computer said this is optimal. |
| Sam | Exactly. Unless you are paying incredibly close attention to the output, it will look like a perfectly plausible mathematical answer for your real world problem. It’s a silent failure of modeling. |
| Alex | Wow. So what does this all mean for you, the listener? We started this deep dive talking about tables and spreadsheets and how they give us a false sense of security when we really need to understand relationships. We’ve learned that visualizing the world as a graph, as nodes and edges, nouns and verbs, unlocks a completely different dimension of problem solving. We’ve seen how breadth-first search ripples out like a pebble in a pond to find the fewest hops, |
| Sam | which is great for unweighted graphs. |
| Alex | Exactly. We’ve seen how analyzing connected components and the empty spaces roots out hidden money laundering rings or weird data errors like our stranded island of Roman numerals, and we’ve seen how D Dyjkstra’s algorithm uses dynamically reshuffling priority cues to help us navigate the complex weighted reality of the physical world. |
| Sam | It really is a paradigm shift in how you view data. It really is. But I want to leave you, the listener, with one final thought based on that discussion we just had about modeling decisions. In our daily lives, algorithms are constantly suggesting the best, the shortest, or the most optimal path for us all the time. Whether that is a GPS routing you through neighborhood traffic. A career networking site suggesting who you should connect with to get a job or a social media feed determining the best piece of information to show you next. The math doesn’t care what the numbers represent. |
| Alex | It just crunches the numbers. |
| Sam | Exactly. So if shortest and best are just mathematical modeling decisions based on invisible weights, the next time an algorithm offers you the optimal path, you have to ask yourself, what exactly did the programmer choose to measure, and just as importantly, what did they decide to value as zero. |
Presentation
Read
- Graphs and Shortest Path (lecture notes)
Hands-on
Notebooks in 12-Graphs-Shortest-Path
Homework
- Homework 11: Fewest Hops — due Wednesday, November 25, 2026