Skip to content

Breadth-first search

networks

Level 2 of 3

Also called BFS.

how it works

The idea, then one run, moment by moment.

Breadth-first search finds the fewest roads from one place to every place it can reach. It spreads like a ripple: first the places one road away, then two, then three. It keeps a queue of places found but not yet taken. Write 0 at the start and put it in the queue. Then take the place at the front, and look along each of its roads in letter order. A place not found yet gets one more than the place just taken. That is its number of roads from the start. It joins the back of the queue. A place found already is passed by. Places leave the queue in the order they joined, so nearer places are always taken first. Each road looked along is one look, and this page counts looks.

ABCDEFGH
The town of eight, the watch page's first example, 8 places and 8 roads. The walk starts at A, shaded.
roads from Aplaces
0A
1B, E
2C, F
3D, G
4H
The town of eight from A, ring by ring. Every place one road away is taken before any place two away.
ABCDEFGH
A map in two pieces, the watch page's fourth example: no road joins the left four to the right four. From E the walk reaches only its own piece, shaded. C, D, G and H get no number. A second walk, from C, would number them, as the Python below does.
A town of eight places: 8 moments of its 34 steps, the steps between them left for the watch page
  1. step 1 of 34

    A0BCDEFGHA

    Start at A. It is 0 roads from itself, so write 0 there and put it in the queue.

    what it remembers to know where it is
    in hand
    not yet
    roads from the start
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 34

    A0B1CDE1FGHABE

    E has not been found yet, so it is one road from the start, one more than A. Write that at E, and put E at the back of the queue.

    what it remembers to know where it is
    in hand
    A
    roads from the start
    0

    watch from here

  3. step 9 of 34

    A0B1C2DE1F2GHBECF

    F has not been found yet, so it is 2 roads from the start, one more than B. Write that at F, and put F at the back of the queue.

    what it remembers to know where it is
    in hand
    B
    roads from the start
    1

    watch from here

  4. step 12 of 34

    A0B1C2DE1F2GHECF

    A has been found already, by no more roads than going through E would take, so pass it by.

    what it remembers to know where it is
    in hand
    E
    roads from the start
    1

    watch from here

  5. step 17 of 34

    A0B1C2D3E1F2G3HCFDG

    G has not been found yet, so it is 3 roads from the start, one more than C. Write that at G, and put G at the back of the queue.

    what it remembers to know where it is
    in hand
    C
    roads from the start
    2

    watch from here

  6. step 21 of 34

    A0B1C2D3E1F2G3HFDG

    G has been found already, by no more roads than going through F would take, so pass it by.

    what it remembers to know where it is
    in hand
    F
    roads from the start
    2

    watch from here

  7. step 29 of 34

    A0B1C2D3E1F2G3H4GH

    H has not been found yet, so it is 4 roads from the start, one more than G. Write that at H, and put H at the back of the queue.

    what it remembers to know where it is
    in hand
    G
    roads from the start
    3

    watch from here

  8. step 34 of 34

    A0B1C2D3E1F2G3H4

    Done. The queue is empty: 8 of the 8 places can be reached, and the number at each is the fewest roads from the start.

    what it remembers to know where it is
    in hand
    not yet
    roads from the start
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. write 0 at the start, and put it in the queuePython lines 26 and 27
  2. while the queue is not empty, take the place at its frontPython lines 28 and 29
  3. look along each road from it, in letter orderPython lines 20, 21 and 30
  4. a place not found yet: write one more than here, and put it at the back of the queuePython lines 31, 32 and 33
  5. a place found already: pass it byPython line 34
  6. the number at each place is the fewest roads from the startPython line 35
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

from collections import deque


def breadth_first_search(roads, start):
    """Find the fewest roads from start to every place it can reach.

    roads is a list of pairs of places, such as ("A", "B"), each road
    running both ways. Returns a dict of each place reached and its
    number of roads from start. A place it cannot reach is left out.
    """
    return walk(neighbours(roads), start)


def neighbours(roads):
    """Each place's neighbours, in letter order."""
    near = {}
    for a, b in roads:  # a road runs both ways
        near.setdefault(a, []).append(b)
        near.setdefault(b, []).append(a)
    for place in near:
        near[place].sort()
    return near


def walk(near, start):
    steps = {start: 0}  # write 0 at the start
    queue = deque([start])  # and put it in the queue
    while queue:  # while the queue is not empty
        here = queue.popleft()  # take the place at its front
        for there in near.get(here, []):  # look along each road from it
            if there not in steps:  # a place not found yet
                steps[there] = steps[here] + 1  # one more than here
                queue.append(there)  # joins the back of the queue
            # a place found already is passed by
    return steps  # each number: the fewest roads from start


def every_piece(roads):
    """Walk the whole map, even one in pieces.

    A walk from one place reaches only its own piece, so start a new
    walk at each place no walk has reached yet. Returns the pieces,
    each its places in letter order.
    """
    near = neighbours(roads)
    found = set()
    pieces = []
    for place in sorted(near):  # every place, in letter order
        if place not in found:  # no walk has reached it: a new piece
            piece = walk(near, place)
            found.update(piece)
            pieces.append(sorted(piece))
    return pieces

how it scales

Roads looked along for maps of 10 to 1,000 places, every place in one piece.

Each mark across or up is ten times the one before, a log-log plot. A line of places climbs one mark up for each mark across: ten times the places, ten times the looks, 198 at 100 places and 1,998 at 1,000. Every pair joined climbs two marks up for each: ten times the places, a hundred times the looks, 9,900 and 999,000.

roads looked along, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, n, ten times more at each mark to the right

  • every pair joined, the most roadssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a line, the fewest roads that join the places in one piecesolid where measured by running it; dashed where its formula carries it on to ten million
what every pair joined costs, at a billion looks a second
nnroads looked alongtime
1,000999,000about 999 microseconds
100,0009,999,900,000about 10 seconds
10,000,00099,999,990,000,000about 1.2 days

The roads looked along are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count breadth-first search's roads looked along yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it walks two maps of n
places in one piece, starting at the first place: a line, the fewest
roads that join them, and every two places joined, the most. It prints
the roads looked along for each. Each place taken from the queue looks
along every road it is on once, found already or not. The counts are the
same on any computer; only the time differs.
"""
from collections import deque


def breadth_first_search(roads, start):
    """Find the fewest roads from start to every place it can reach.

    roads is a list of pairs of places, such as ("A", "B"), each road
    running both ways. Returns a dict of each place reached and its
    number of roads from start. A place it cannot reach is left out.
    """
    return walk(neighbours(roads), start)


def neighbours(roads):
    """Each place's neighbours, in letter order."""
    near = {}
    for a, b in roads:  # a road runs both ways
        near.setdefault(a, []).append(b)
        near.setdefault(b, []).append(a)
    for place in near:
        near[place].sort()
    return near


def walk(near, start):
    steps = {start: 0}  # write 0 at the start
    queue = deque([start])  # and put it in the queue
    while queue:  # while the queue is not empty
        here = queue.popleft()  # take the place at its front
        for there in near.get(here, []):  # look along each road from it
            if there not in steps:  # a place not found yet
                steps[there] = steps[here] + 1  # one more than here
                queue.append(there)  # joins the back of the queue
            # a place found already is passed by
    return steps  # each number: the fewest roads from start


def every_piece(roads):
    """Walk the whole map, even one in pieces.

    A walk from one place reaches only its own piece, so start a new
    walk at each place no walk has reached yet. Returns the pieces,
    each its places in letter order.
    """
    near = neighbours(roads)
    found = set()
    pieces = []
    for place in sorted(near):  # every place, in letter order
        if place not in found:  # no walk has reached it: a new piece
            piece = walk(near, place)
            found.update(piece)
            pieces.append(sorted(piece))
    return pieces


def count(roads, start):
    """How many roads the walk from start looks along: the walk above,
    with one added for each road it looks along."""
    near = neighbours(roads)
    looks = 0
    steps = {start: 0}
    queue = deque([start])
    while queue:
        here = queue.popleft()
        for there in near.get(here, []):
            looks += 1
            if there not in steps:
                steps[there] = steps[here] + 1
                queue.append(there)
    return looks


def line(n):
    """n places in a line, p1 to pn: n - 1 roads."""
    return [(f"p{k}", f"p{k + 1}") for k in range(1, n)]


def every_pair(n):
    """n places, every two joined: n(n - 1) / 2 roads."""
    return [(f"p{a}", f"p{b}") for a in range(1, n + 1) for b in range(a + 1, n + 1)]


if __name__ == "__main__":
    print(f"{'n':>6} {'a line':>8} {'every pair':>12}")
    for n in [10, 100, 1000]:
        print(f"{n:>6} {count(line(n), 'p1'):>8} {count(every_pair(n), 'p1'):>12}")

best, worst and average

The cases are maps in one piece, so every place is reached. A map in pieces looks only along its start's piece, and is set aside here. The walk looks along each road twice, once from each end. So the roads decide the cost, not the places alone. Few roads, few looks. An average map is not worked out here; it costs between the two.

A case is one kind of map, such as a line, however many places. A bound says how fast that case's cost grows as more places are added.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta line, the fewest roads that join the places in one pieceworstevery pair joined, the most roads
roads looked along2(n−1)2(n - 1), each of the line's n−1n - 1 roads twicen(n−1)n(n - 1), each of the n(n−1)2\frac{n(n - 1)}{2} roads twice
how the roads looked along grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: a number at each place and a queue of at most nn places, each joining at most once (section 4's first question, line 1)

Extra memory is the room it needs on top of the input itself, while it runs.

A1B2C2D2E1
A line of 5 places, 4 roads. The degrees add to 8, so the walk looks along 8 roads.
A4B4C4D4E4
The same 5 places, every pair joined, 10 roads. Each place has degree 4, so the walk looks along 20.
placesa lineevery pair
222
346
4612
5820
61030
81456
101890
1001989,900
1,0001,998999,000
Roads looked along, the walk's own count. Double the places and a line's looks about double; every pair's about quadruple. At 1,000 places a line looks about twice nn times, every pair about nn times nn.

where the formula comes from

Each count above, worked out line by line. Each reason names the line it uses.

On a map in one piece with mm roads, why does the walk look along 2m2m roads?
  1. the move: joins once, taken once

    the line:
    each place found joins thequeue once, and is taken once\begin{gathered} \text{each place found joins the} \\ \text{queue once, and is taken once} \end{gathered}

    why it is allowed: A place joins when it is first found, and a place found already is passed by. The walk runs until the queue is empty, so each place that joins also leaves, and is taken once.

  2. the move: in one piece, every place found

    the line:
    in one piece, everyplace is found\begin{gathered} \text{in one piece, every} \\ \text{place is found} \end{gathered}
    ABCD
    A route from the start, A. Say A and B are found, shaded, and C is the first not found. B is taken and looks along B-C, so C is found too.

    why it is allowed: Follow a route from the start to any place. The first place on it not found yet comes just after a found place. That one is taken, by line 1, and looks along the road between them, so it is found after all.

  3. the move: each of its roads

    the line:
    a place taken looks alongeach of its roads once\begin{gathered} \text{a place taken looks along} \\ \text{each of its roads once} \end{gathered}
    place takenroads it looks along
    A2
    B3
    E1
    C3
    F2
    D1
    G3
    H1
    all16
    The town of eight from A, in the order taken. Its 8 roads give 16 looks.

    why it is allowed: It looks along every road it is on, found or not. So its looks are its degree.

  4. the move: add up the degrees

    the line:
    L is every place’sdegree, added up\begin{gathered} L \text{ is every place's} \\ \text{degree, added up} \end{gathered}

    why it is allowed: LL is the roads looked along. By lines 1 and 2 every place is taken once, and by line 3 each looks along its degree.

  5. the move: count each road at both ends

    the line:
    L=2+2+⋯+2L = 2 + 2 + \dots + 2

    why it is allowed: By line 4. A road has two ends, and both are taken, so it is looked along twice: mm twos, the dots standing for those not written.

  6. the move: add the twos

    the line:
    L=2mL = 2m
    where does this come from?
    question 1 of the page graphs and their wordsA map has mm roads. What do the degrees of its places add to?
    1. the move: count each road at both ends

      the line:
      S=2+2+⋯+2S = 2 + 2 + \dots + 2
      A2B3C2D2E3F2
      The map of 6 places, each place's degree written above it.

      why it is allowed: Let SS be the degrees added up. Every road has two ends, and it counts once at the place on each end, 2 in all. So mm roads give mm twos, the dots standing for the twos not written. For 7 roads, 7 twos.

    2. the move: add the twos

      the line:
      S=2mS = 2m

      why it is allowed: mm twos make twice mm.

    3. the move: read it

      the line:
      7 roads:degrees add to 14\begin{gathered} 7 \text{ roads:} \\ \text{degrees add to 14} \end{gathered}
      placedegree
      A2
      B3
      C2
      D2
      E3
      F2
      all14
      The degrees of the 6 places, added. 14 is twice the 7 roads.

      why it is allowed: The map has 7 roads, and its degrees add to 14, twice 7.

    4. the move: odd degrees come in pairs

      the line:
      places of odd degree:an even number of them\begin{gathered} \text{places of odd degree:} \\ \text{an even number of them} \end{gathered}

      why it is allowed: Line 2's total is twice mm, so it is even. In line 3's table, 14 is 8 from the even degrees and 6 from the odd ones, B's and E's. 14 and 8 are even, so 6 is too. Odd numbers add to an even number only in pairs. 3 + 3 is 6, but 3 + 3 + 1 is 7.

    the whole page: graphs and their words

    why it is allowed: mm twos make twice mm. The degrees of any map add to twice its roads, in this line's fold. For the town of eight, 8 roads, 16 looks.

  7. the move: count the takes too

    the line:
    V takes and 2E looks:V+2E in all\begin{gathered} V \text{ takes and } 2E \text{ looks:} \\ V + 2E \text{ in all} \end{gathered}
    the town of eightcount
    VV takes8
    2E2E looks16
    V+2EV + 2E24
    V+EV + E16
    2V+2E2V + 2E32
    The town of eight, 8 places and 8 roads. Its 24 takes and looks lie between 16 and 32.

    why it is allowed: Taking a place is work too, so count it with the looks. Books write VV for the places, here nn, and EE for the roads, here mm. Lines 1 and 2 take each place once, VV takes, and line 6 gives 2E2E looks.

  8. the move: a floor

    the line:
    V+E is at mostV+2E\begin{gathered} V + E \text{ is at most} \\ V + 2E \end{gathered}

    why it is allowed: Take EE away from line 7's total, and EE is not below 0. For the town of eight, 16 is at most 24.

  9. the move: a ceiling

    the line:
    V+2E is at most2V+2E\begin{gathered} V + 2E \text{ is at most} \\ 2V + 2E \end{gathered}

    why it is allowed: Add VV to line 7's total, and VV is not below 0. 2V+2E2V + 2E is twice V+EV + E. For the town, 24 is at most 32.

  10. the move: read the floor as a bound

    the line:
    takes and looks inΩ(V+E)\begin{gathered} \text{takes and looks in} \\ \Omega(V + E) \end{gathered}

    why it is allowed: By line 8, with the fixed multiple 1, on every map in one piece.

  11. the move: read the ceiling as a bound

    the line:
    takes and looks inO(V+E)\begin{gathered} \text{takes and looks in} \\ O(V + E) \end{gathered}

    why it is allowed: By line 9, with the fixed multiple 2, on every map in one piece.

  12. the move: ceiling and floor together

    the line:
    tight:Θ(V+E)\begin{gathered} \text{tight:} \\ \Theta(V + E) \end{gathered}

    why it is allowed: Lines 10 and 11 bound the takes and looks by the same growth, V+EV + E, on every map in one piece.

try it with a small mm: at m=8m = 8, line 5 gives L=16L = 16, which you can work out by hand

Why does a line of nn places cost 2(n−1)2(n - 1) looks, the fewest for a map in one piece?
  1. the move: a line's roads

    the line:
    a line of n places:n−1 roads\begin{gathered} \text{a line of } n \text{ places:} \\ n - 1 \text{ roads} \end{gathered}
    ABCDE
    5 places, 4 roads, in one piece. Take any road away and it falls into two pieces.

    why it is allowed: The first place needs no road, and each place after it adds one, to the place before.

  2. the move: twice each road

    the line:
    K=2+2+⋯+2K= 2 + 2 + \dots + 2

    why it is allowed: KK is the looks on a line. By the first question each road is looked along twice, and by line 1 there are n−1n - 1 roads.

  3. the move: add the twos

    the line:
    K=2(n−1)K= 2(n - 1)

    why it is allowed: n−1n - 1 twos make twice n−1n - 1. For 5 places, 8.

  4. the move: open the bracket

    the line:
    K=2n−2K= 2n - 2

    why it is allowed: Twice nn, less twice 1. For 5, 10 less 2.

  5. the move: a ceiling

    the line:
    K≤2nK\le 2n

    why it is allowed: By line 4, without the 2 taken away.

  6. the move: read it as a bound

    the line:
    K∈O(n)K\in O(n)

    why it is allowed: By line 5, with the fixed multiple 2.

  7. the move: a floor

    the line:
    K≥nK\ge n

    why it is allowed: By line 4, 2n−22n - 2 is nn plus n−2n - 2, which is not below 0 from 2 places on. For 5, 8 is at least 5.

  8. the move: read it as a bound

    the line:
    K∈Ω(n)K\in \Omega(n)

    why it is allowed: By line 7, with the fixed multiple 1, from 2 places on.

  9. the move: ceiling and floor together

    the line:
    K∈Θ(n)K\in \Theta(n)

    why it is allowed: Lines 6 and 8 bound KK by the same growth, nn.

  10. the move: a line has the fewest roads

    the line:
    K=2(n−1)K= 2(n - 1)
    where does this come from?
    question 3 of the page graphs and their wordsnn places in one piece, on two-way roads. How few roads can join them?
    1. the move: start with no roads

      the line:
      no roads:n pieces\begin{gathered} \text{no roads:} \\ n \text{ pieces} \end{gathered}

      why it is allowed: With no roads, each place is a piece on its own.

    2. the move: a road joins two pieces at most

      the line:
      each road:at most one piece fewer\begin{gathered} \text{each road:} \\ \text{at most one piece fewer} \end{gathered}
      ABCDEFG
      7 places and 6 roads, yet two pieces. Laid after A to B, A to C and B to D, the road C to D joins two places already in one piece, so it joins nothing new.

      why it is allowed: A road between two pieces makes them one. A road inside one piece joins nothing new.

    3. the move: count the pieces left

      the line:
      after k roads:at least n−k pieces\begin{gathered} \text{after } k \text{ roads:} \\ \text{at least } n - k \text{ pieces} \end{gathered}
      roads laidroadpieces
      0none yet7
      1A to B6
      2A to C5
      3B to D4
      4C to D4
      5E to F3
      6E to G2
      The 7 places above, their 6 roads laid one at a time. The fourth, C to D, takes no piece away. 6 roads leave 2 pieces.

      why it is allowed: Lay the roads one at a time, and let kk be how many are laid. Start at nn pieces and take off at most 1 for each road.

    4. the move: ask for one piece

      the line:
      one piece:n−k is at most 1\begin{gathered} \text{one piece:} \\ n - k \text{ is at most 1} \end{gathered}

      why it is allowed: Line 3's pieces can be 1 only if n−kn - k is 1 or less.

    5. the move: turn it round

      the line:
      k is at least n−1\begin{gathered} k \text{ is at least } n - 1 \end{gathered}

      why it is allowed: When n−kn - k is at most 1, kk falls short of nn by at most 1. So fewer than n−1n - 1 roads always leave two pieces or more. For 6 places, 4 roads take off at most 4 of the 6 pieces, so at least 2 are left.

    6. the move: a line of places is enough

      the line:
      join each place to the next:n−1 roads, one piece\begin{gathered} \text{join each place to the next:} \\ n - 1 \text{ roads, one piece} \end{gathered}
      ABCDEF
      6 places, each joined to the next, drawn heavy. 5 roads hold them in one piece.

      why it is allowed: Each place after the first has one road back to the one before it. That is n−1n - 1 roads, and every place reaches the first.

    7. the move: the fewest

      the line:
      R=n−1R = n - 1

      why it is allowed: Let RR be the fewest roads. Line 5 says no fewer than n−1n - 1 will do, and line 6 that n−1n - 1 do.

    the whole page: graphs and their words

    why it is allowed: Line 3 again. This line's fold shows that nn places in one piece need at least n−1n - 1 roads, and by line 1 a line has exactly n−1n - 1, so it has the fewest.

  11. the move: any map in one piece

    the line:
    any map in one piece:m is at least n−1\begin{gathered} \text{any map in one piece:} \\ m \text{ is at least } n - 1 \end{gathered}

    why it is allowed: By line 10's fold.

  12. the move: double both

    the line:
    2m is at least 2(n−1)2m \text{ is at least } 2(n - 1)

    why it is allowed: Twice each side of line 11.

  13. the move: compare with the line

    the line:
    its 2m looks areat least K\begin{gathered} \text{its } 2m \text{ looks are} \\ \text{at least } K \end{gathered}

    why it is allowed: By the first question it looks along 2m2m roads, and by line 3 KK is 2(n−1)2(n - 1). So by line 12 no map in one piece costs less than a line.

try it with a small nn: at n=5n = 5, line 2 gives K=8K = 8, which you can work out by hand

Why does a map with every pair joined cost n(n−1)n(n - 1) looks, the most?
  1. the move: count the roads place by place

    the line:
    roads:(n−1)+⋯+2+1\begin{gathered} \text{roads:} \\ (n - 1) + \dots + 2 + 1 \end{gathered}
    A3B3C3D3
    4 places, every pair joined, each of degree 3. A has 3 new roads, B 2 more, C 1 more, 6 in all. The walk looks along 12.

    why it is allowed: The first place has roads to the n−1n - 1 others, the next adds one fewer new road, and the last adds none.

  2. the move: twice each road

    the line:
    W=2((n−1)+⋯+2+1)W = 2 \left( (n - 1) + \dots + 2 + 1 \right)

    why it is allowed: WW is the looks with every pair joined. By the first question, twice line 1's roads.

  3. the move: add up 1 to n - 1

    the line:
    W=2⋅n(n−1)2W = 2 \cdot \frac{n(n - 1)}{2}
    where does this come from?
    question 2 of the page graphs and their wordsnn places, every two joined by a road. How many roads?
    1. the move: count place by place

      the line:
      R=(n−1)+⋯+2+1R = (n - 1) + \dots + 2 + 1
      ABCDE
      Every two of 5 places joined. A has 4 roads, B 3 more, C 2 more, D 1 more, E none new. 4 + 3 + 2 + 1 = 10.

      why it is allowed: Let RR be the roads, for 2 places or more. List the places. The first has roads to the n−1n - 1 after it. The next adds one fewer new road, as its road to the first is counted already. Each adds one fewer, and the last adds none.

    2. the move: use adding up 1 to n

      the line:
      R=n(n−1)2R = \frac{n(n - 1)}{2}
      placenew roads
      A4
      B3
      C2
      D1
      E0
      all10
      The new roads each place adds on line 1's map, in turn. 4 + 3 + 2 + 1 + 0 = 10.
      where does this come from?
      question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

        the line:
        S=1+2+⋯+nS = 1 + 2 + \dots + n

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

        why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: Read from right to left, line 1 is 1 + 2 + up to n−1n - 1. The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is n−1n - 1. One more than it is nn, so RR is n−1n - 1 times nn, halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.

    3. the move: one way, each pair holds two

      the line:
      one way:U is twice R\begin{gathered} \text{one way:} \\ U \text{ is twice } R \end{gathered}

      why it is allowed: Let UU be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.

    4. the move: double line 2

      the line:
      U=2R=n(n−1)U = 2R = n(n - 1)

      why it is allowed: Line 3 says UU is 2R2R, and twice line 2 is n(n−1)n(n - 1). For 5 places, 20.

    5. the move: read it

      the line:
      5 places: 10 roads, or 20 one way1,000 places: 499,500 roads\begin{gathered} 5 \text{ places: 10 roads, or 20 one way} \\ 1{,}000 \text{ places: } 499{,}500 \text{ roads} \end{gathered}

      why it is allowed: 1,000 times 999, halved, is 499,500. A map of 1,000 places with 3,000 roads has 3 times as many roads as places, a few, so it is sparse. It holds 3,000 of the 499,500 it could.

    the whole page: graphs and their words

    why it is allowed: The roads add to n(n−1)2\frac{n(n - 1)}{2}, in this line's fold. For 4 places, 4 times 3 over 2 is 6.

  4. the move: twice a half is 1

    the line:
    W=n(n−1)W = n(n - 1)

    why it is allowed: By line 3, the 2 and the half cancel. For 4, 12.

  5. the move: open the bracket

    the line:
    W=n2−nW = n^2 - n

    why it is allowed: nn times nn, less nn times 1. For 4, 16 less 4.

  6. the move: a ceiling

    the line:
    W≤n2W \le n^2

    why it is allowed: By line 5, without the nn taken away.

  7. the move: read it as a bound

    the line:
    W∈O(n2)W \in O(n^2)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: a floor

    the line:
    W≥n22W \ge \frac{n^2}{2}

    why it is allowed: By line 5. For 4, 16 less 4 is 12, and half of 16 is 8. In general, n2−nn^2 - n less half of n2n^2 is half of n2n^2 less nn, not below 0 from 2 places on.

  9. the move: read it as a bound

    the line:
    W∈Ω(n2)W \in \Omega(n^2)

    why it is allowed: By line 8, with the fixed multiple a half, from 2 places on.

  10. the move: ceiling and floor together

    the line:
    W∈Θ(n2)W \in \Theta(n^2)

    why it is allowed: Lines 7 and 9 bound WW by the same growth, n2n^2.

  11. the move: no map has more roads

    the line:
    any map of n placesin one piece:m is at most n(n−1)2\begin{gathered} \text{any map of } n \text{ places} \\ \text{in one piece:} \\ m \text{ is at most } \frac{n(n - 1)}{2} \end{gathered}

    why it is allowed: A map here has at most one road between two places and none from a place to itself, as the page on graphs and their words sets out. With every pair joined, any two places already have their road. So no map of nn places has more than line 3's n(n−1)2\frac{n(n - 1)}{2}. For 4 places, 6.

  12. the move: double both

    the line:
    2m is at most 2⋅n(n−1)22m \text{ is at most } 2 \cdot \frac{n(n - 1)}{2}

    why it is allowed: Twice each side of line 11.

  13. the move: twice a half is 1

    the line:
    2m is at most n(n−1)2m \text{ is at most } n(n - 1)
    a map of 4 placesroadslooks
    a line, A-B-C-D36
    a loop, A-B-C-D and back to A48
    every pair612
    Maps of 4 places in one piece. Every pair has the most roads, so the most looks, WW at 12.

    why it is allowed: By line 12, the 2 and the half cancel, as in line 4.

  14. the move: compare with every pair

    the line:
    the walk’s 2m looks areat most W\begin{gathered} \text{the walk's } 2m \text{ looks are} \\ \text{at most } W \end{gathered}

    why it is allowed: By the first question the walk on such a map looks along 2m2m roads, and by line 4 WW is n(n−1)n(n - 1). So by line 13 no map of nn places in one piece costs more than WW.

try it with a small nn: at n=4n = 4, line 2 gives W=12W = 12, which you can work out by hand

On a map in one piece kept as a grid, why does the walk check n2n^2 cells?
  1. the move: a row for each place

    the line:
    T=n+n+⋯+nT = n + n + \dots + n
    AABBCCDDEE
    ABBACCBDDCEED
    A line of 5 places as a grid and as lists, B framed. The grid checks all 5 cells of B's row. The lists read B's own box, then A and C, 3 boxes.
    placeslooks on a linecells checked in a grid
    5825
    1018100
    10019810,000
    A line kept as a grid. From 10 places to 100: about ten times the looks, a hundred times the cells.

    why it is allowed: TT is the cells checked. By the first question's lines 1 and 2 each of the nn places is taken once. Its row has a cell for every place, and it checks them all.

  2. the move: add them up

    the line:
    T=n2T = n^2

    why it is allowed: nn added nn times is nn times nn. For a line of 5 places, 25 cells, against 8 looks.

try it with a small nn: at n=5n = 5, line 1 gives T=25T = 25, which you can work out by hand

count it yourself

Count every road looked along as the walk crosses a line of 5 places, A, B, C, D and H, from A. The watch page's grid names its fifth place H. Its box writes the map as A-B, B-C, C-D, D-H; A, the start after the semicolon.

A-B, B-C, C-D, D-H; A, every step written down
stepthe queue, front firstwhat happensroads looked along
1AStart at A. It is 0 roads from itself, so write 0 there and put it in the queue.A0
2Take A from the front of the queue. It is 0 roads from the start.0
3BB has not been found yet, so it is one road from the start, one more than A. Write that at B, and put B at the back of the queue.B1
4BEvery road from A has been looked along, so A is done.B1
5Take B from the front of the queue. It is one road from the start.1
6A has been found already, by no more roads than going through B would take, so pass it by.2
7CC has not been found yet, so it is 2 roads from the start, one more than B. Write that at C, and put C at the back of the queue.C3
8CEvery road from B has been looked along, so B is done.C3
9Take C from the front of the queue. It is 2 roads from the start.3
10B has been found already, by no more roads than going through C would take, so pass it by.4
11DD has not been found yet, so it is 3 roads from the start, one more than C. Write that at D, and put D at the back of the queue.D5
12DEvery road from C has been looked along, so C is done.D5
13Take D from the front of the queue. It is 3 roads from the start.5
14C has been found already, by no more roads than going through D would take, so pass it by.6
15HH has not been found yet, so it is 4 roads from the start, one more than D. Write that at H, and put H at the back of the queue.H7
16HEvery road from D has been looked along, so D is done.H7
17Take H from the front of the queue. It is 4 roads from the start.7
18D has been found already, by no more roads than going through H would take, so pass it by.8
19Every road from H has been looked along, so H is done.8
20Done. The queue is empty: 5 of the 5 places can be reached, and the number at each is the fewest roads from the start.8

In all, 8 roads looked along. The formula from section 4, 2(n−1)2(n - 1), gives K=8K = 8 at n=5n = 5: the same.

where you meet it

Two widely used Python libraries walk networks breadth first.

  • networkx's fewest roads

    networkx, a library for measuring networks of things, gives the fewest roads from one place to every place it can reach, on a map whose roads have no lengths. It works ring by ring from the start, as this walk does.

    source: the networkx source, unweighted.py (opens in a new tab), its single_source_shortest_path_length

  • SciPy's breadth-first order

    SciPy, a library for science and maths, lists a map's places in breadth-first order from a start. Beside each place it can give the one it was reached from.

    source: the SciPy reference, scipy.sparse.csgraph.breadth_first_order (opens in a new tab)

placereached fromroads from A
Anone0
BA1
EA1
CB2
FB2
DC3
GC3
HG4
The town of eight, as SciPy would list it from A. Follow the reached-from column back from H, to G, C, B and A, a fewest-road route.
9222ADBC
Fewest roads is not shortest. A to D is 1 road of 9, but the 3 roads through B and C are 6 in all, drawn heavy.

what is used instead

When roads have lengths, the fewest roads can be the longer trip. Dijkstra's method finds the shortest trip instead. Breadth-first search is the one to use when every road counts the same.

how it compares

Two walks of the same map, set side by side by what each writes and what each costs.

walkkeeps its places inwhat it does nextwrites at each placeroads looked along, in one piece
breadth-first searcha queue, oldest firstevery road of the oldestfewest roads from the start2m2m
depth-first searcha stack, newest on topone road from the newest, back when none is leftthe order reached2m2m
The two walks take a different place next and go a different way. Depth-first also takes each place once and looks along each of its roads once. So section 4's first question holds for it too: on a map in one piece both look along every road twice. Only breadth-first's numbers are fewest roads.
foundbreadth-first searchdepth-first search
1stAA
2ndBB
3rdEC
4thCD
5thFG
6thDF
7thGH
8thHE
The town of eight from A, each walk's places in the order it finds them. Breadth-first finds E third, one road from A; depth-first goes deep and finds E last.

race them on one row of your own