Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
A graph is people plus friendships. Breadth-first search spreads from one person like ripples in a pond, using a queue, and gives the fewest hops to everyone. Emma's friend network, step by step, then a million users with the same code.
What you will learn
- Describe a graph and store it as an adjacency list
- Explain how BFS uses a queue to visit people level by level
- Explain why the seen check stops the search and keeps the hops correct
- State the cost of BFS as O(V + E) and name where it is used
Before you start
- Queues (first in, first out)
- Python lists and dictionaries
Emma uses a friend app. The app wants to show "people you may know": people who aren't Emma's friends yet, but are friends of her friends. So the question is, how many hops is each person from Emma? A friend is one hop, and a friend of a friend is two hops. The answer we want: Kate is two hops away, and so is Lucy.
People plus friendships make what we call a graph. Each person is a node, and each friendship is an edge between two nodes.
Ripples in a pond
Imagine the people standing in a pond, and a stone drops right at Emma. The first ring of water reaches Jack and Tom. The second ring reaches Kate and Lucy, two rings away, so they're friends of friends. The third ring reaches Mark, three rings away. The water spreads level by level.
A computer can't watch water, so it keeps a waiting line, a queue. The first person reached is the first person asked about their friends. That's breadth-first search, or BFS: level by level, like ripples, with a queue keeping the order.
Storing a graph: one list per person
The computer keeps one list for each person. Emma's list is Jack and Tom. Jack's list is Emma, Kate and Tom, and so on. Asking for Emma's friends is just reading her list. A friendship goes both ways: Emma is in Jack's list, and Jack is in Emma's list. One list of friends per person is called an adjacency list.
class Friends:
def __init__(self):
self.lists = {} # each name points to a list of friends
def add(self, a, b): # friends both ways
self.lists.setdefault(a, [])
self.lists.setdefault(b, [])
self.lists[a].append(b)
self.lists[b].append(a)
def of(self, who):
return self.lists[who]
A dict maps each name to its list. setdefault gives a new name an empty list, and add puts the friendship in both lists.
BFS in Python
from collections import deque
def bfs(g, start):
hops = {}
queue = deque()
hops[start] = 0
queue.append(start)
while queue:
who = queue.popleft()
for f in g.of(who):
if f not in hops: # not seen yet
hops[f] = hops[who] + 1
queue.append(f)
return hops
hops records every person we've seen and how far they are. Emma starts at zero and joins the queue. While the queue isn't empty, take the person at the front. For each friend, ask "have we seen this friend already?" If not, the friend gets one hop more and joins the back of the queue. First in, first out, so everyone one hop away is done before anyone two hops away.
from friends import Friends
from bfs import bfs
friends = Friends()
friends.add("Emma", "Jack")
friends.add("Emma", "Tom")
friends.add("Jack", "Kate")
friends.add("Jack", "Tom")
friends.add("Tom", "Lucy")
friends.add("Lucy", "Mark")
print(f"Emma's friends: [{', '.join(friends.of('Emma'))}]")
hops = bfs(friends, "Emma")
for who in hops:
print(f"{who}: hops = {hops[who]}")
Emma's friends: [Jack, Tom]
Emma: hops = 0
Jack: hops = 1
Tom: hops = 1
Kate: hops = 2
Lucy: hops = 2
Mark: hops = 3
Step by step
| Take from front | Friends checked | New (hops) | Queue after |
|---|---|---|---|
| (start) | Emma (0) | Emma | |
| Emma | Jack, Tom | Jack (1), Tom (1) | Jack, Tom |
| Jack | Emma, Kate, Tom | Kate (2) | Tom, Kate |
| Tom | Emma, Jack, Lucy | Lucy (2) | Kate, Lucy |
| Kate | Jack | nobody | Lucy |
| Lucy | Tom, Mark | Mark (3) | Mark |
| Mark | Lucy | nobody | empty, done |
Kate and Lucy are two hops away, exactly the answer we wanted. Because everyone one hop away was finished before anyone two hops away, these hops are the fewest possible.
No note, no end
The if f not in hops line matters more than it looks. Take three friends who all know each other: Emma, Jack and Tom, and forget to check who was seen. Emma starts the line; Jack and Tom join. Take Jack: Emma and Tom join again, now claiming two hops. Take Tom: Emma and Jack join again. In a ring of friends, the line never ends, and the hop counts are wrong.
The fix is a note. Every person gets a note the first time they join the line, and we ask "seen already?" before anyone joins. With the note, Jack's turn adds nobody, Tom's turn adds nobody, and the line empties. The note is what makes the search stop, and it keeps the hops true.
A million people
from friends import Friends
from bfs import bfs
for n in (100, 10_000, 1_000_000):
friends = Friends()
for i in range(1, n): # user i joins
friends.add(f"user{i}", f"user{(i - 1) // 2}")
hops = bfs(friends, "user0")
far = max(hops.values())
print(f"{len(hops):9,d} people, farthest {far} hops")
100 people, farthest 6 hops
10,000 people, farthest 13 hops
1,000,000 people, farthest 19 hops
Each new user joins as a friend of one user already there. The crowd got ten thousand times bigger, but the ripples went only about three times further. The same BFS handles all three sizes.
What it costs
V is the number of people and E the number of friendships.
| Step | Cost |
|---|---|
Take the next person from the front (popleft) | O(1) |
| Look at one friend and check the note | O(1) |
| Each person joins and leaves the queue | once each, O(V) |
| Each friendship is checked | twice, once from each end, O(E) |
| Whole BFS | O(V + E) |
With six people and six friendships, that's six turns and twelve looks. The fewest hops come out on the way, for free. If someone has no path of friends to Emma, the ripples never reach them, so they get no hops at all.
Where you meet BFS
- Friend suggestions: people one or two hops from you are the best guesses.
- The fewest stops on a metro map: the first time the search reaches your station, it used the fewest stops.
- A web crawler: start at one page and follow links, nearest pages first.
- Puzzles in the fewest moves: every position is a node, every move an edge.
Different places, one idea: spread out level by level, and the first time you arrive is the shortest way. For going deep down one path first instead, see depth-first search.
Try it yourself
Add a friendship between Emma and Lucy, run the friends app again, and see whose hops change.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
