Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Data Structures

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Structures

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.

Emma's friend graph: Emma is friends with Jack and Tom (1 hop); Jack and Tom are friends; Jack knows Kate and Tom knows Lucy (2 hops); Lucy knows Mark (3 hops) Emma Jack Tom Kate Lucy Mark 0 hops 1 hop 2 hops 3 hops
Each colour is one ripple. BFS finishes every 1-hop person before any 2-hop person.

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 frontFriends checkedNew (hops)Queue after
(start)Emma (0)Emma
EmmaJack, TomJack (1), Tom (1)Jack, Tom
JackEmma, Kate, TomKate (2)Tom, Kate
TomEmma, Jack, LucyLucy (2)Kate, Lucy
KateJacknobodyLucy
LucyTom, MarkMark (3)Mark
MarkLucynobodyempty, 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.

StepCost
Take the next person from the front (popleft)O(1)
Look at one friend and check the noteO(1)
Each person joins and leaves the queueonce each, O(V)
Each friendship is checkedtwice, once from each end, O(E)
Whole BFSO(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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 10 of 21

Previous
Heaps and Priority Queues: Most Urgent First, Without Searching the Room
Next post
Big-O: Reading Cost From Code, With Handshakes and a Guest Book

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.

On this page

  • Ripples in a pond
  • Storing a graph: one list per person
  • BFS in Python
  • Step by step
  • No note, no end
  • A million people
  • What it costs
  • Where you meet BFS
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.