Skip to content

Depth-first search

networks

Level 2 of 3

Also called DFS.

how it works

The idea, then one run, moment by moment.

Depth-first search begins at one place, the start. It reaches every place it can from there, and numbers them in the order it gets there. Its rule: keep going until you cannot, then back up. It keeps a stack of places. Write 1 at the start and put it on the stack. The place on top looks along its next road, taking its roads in letter order of the places they lead to. A place not reached yet gets the next number and goes on top, so the walk moves there. A place reached already is passed by. A place with no road left comes off the stack, and the walk steps back to the place below. So the stack always holds the route from the start to the place on top. Each road looked along is one look, and this page counts looks. In the town of eight's moments, after the three pictures below, in hand is the place doing the looking. Just after a new place goes on, that is still the place under it on the stack. At the town's step 6, D is on top and C is in hand.

stepwhat happensthe stack, bottom first
1write 1 at AA
2A looks along A-B: B not reached, write 2A, B
3B looks along B-A: A reached, pass byA, B
4B looks along B-C: C not reached, write 3A, B, C
5C looks along C-B: B reached, pass byA, B, C
6C has no road left: off, step back to BA, B
7B has no road left: off, step back to AA
8A has no road left: offempty
A line of 3 places, A-B and B-C, walked from A, every move. 2 roads, 4 looks, 3 places come off.
A1B2C3D4EF6G5H
The town of eight just after F is reached. Each place shows its letter, then its number if it has one. The stack is A, B, C, G, F, drawn heavy, the route from A to the place on top. D has already come off, and H and E are still to come.
A2B3C1D2E1F4G4H3
A map in two pieces. Each place shows its letter and its number. The walk from E reaches only the shaded piece: E 1, A 2, B 3, F 4. So start again, a new walk at C, numbering from 1: C 1, D 2, H 3, G 4. Two walks, two pieces, as the part named every_piece does in the Python below.
A town of eight places: 8 moments of its 26 steps, the steps between them left for the watch page
  1. step 1 of 26

    A1BCDEFGHA

    Start at A. It is the first place reached, so write 1 there and put it on the stack.

    what it remembers to know where it is
    in hand
    not yet
    places reached
    1

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

    watch from here

  2. step 6 of 26

    A1B2C3D4EFGHABCD

    D has not been reached yet, so follow the road from C to it. D is place number 4 to be reached: write 4 there, and put D on top of the stack.

    what it remembers to know where it is
    in hand
    C
    places reached
    4

    watch from here

  3. step 7 of 26

    A1B2C3D4EFGHABCD

    C has been reached already, so pass it by and stay at D.

    what it remembers to know where it is
    in hand
    D
    places reached
    4

    watch from here

  4. step 8 of 26

    A1B2C3D4EFGHABC

    Every road from D has been looked along, so take D off the stack and step back to C.

    what it remembers to know where it is
    in hand
    C
    places reached
    4

    watch from here

  5. step 11 of 26

    A1B2C3D4EF6G5HABCGF

    F has not been reached yet, so follow the road from G to it. F is place number 6 to be reached: write 6 there, and put F on top of the stack.

    what it remembers to know where it is
    in hand
    G
    places reached
    6

    watch from here

  6. step 15 of 26

    A1B2C3D4EF6G5H7ABCGH

    H has not been reached yet, so follow the road from G to it. H is place number 7 to be reached: write 7 there, and put H on top of the stack.

    what it remembers to know where it is
    in hand
    G
    places reached
    7

    watch from here

  7. step 22 of 26

    A1B2C3D4E8F6G5H7AE

    E has not been reached yet, so follow the road from A to it. E is place number 8 to be reached: write 8 there, and put E on top of the stack.

    what it remembers to know where it is
    in hand
    A
    places reached
    8

    watch from here

  8. step 26 of 26

    A1B2C3D4E8F6G5H7

    Done. 8 of the 8 places can be reached, and the numbers give the order they were reached.

    what it remembers to know where it is
    in hand
    not yet
    places reached
    8

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

    watch from here

the steps, in plain words
  1. write 1 at the start, and put it on the stackPython lines 23 and 24
  2. while the stack is not empty, follow the next road from the place on top, in letter orderPython lines 17, 18, 26, 27, 28, 29, 30 and 31
  3. to a place not reached yet: write the next number there, and put it on top of the stackPython lines 32, 33 and 34
  4. to a place reached already: pass it byPython line 35
  5. no road left from it: take it off the stack, and step backPython lines 36 and 37
  6. the numbers give the order the places were reachedPython line 38
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.

def depth_first_search(roads, start):
    """Number the places in the order a deep walk from start reaches them.

    roads is a list of pairs of places, such as ("A", "B"), each road
    running both ways. Returns a dict, a table, of each place reached
    and its number, the start 1. 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):
    reached = {start: 1}  # write 1 at the start
    stack = [start]  # and put it on the stack
    looked = {}  # how many of each place's roads it has looked along
    while stack:  # while the stack is not empty
        here = stack[-1]  # the place on top
        k = looked.get(here, 0)  # how many it has looked along so far
        if k < len(near.get(here, [])):  # it has a road left
            looked[here] = k + 1
            there = near[here][k]  # follow its next road, in letter order
            if there not in reached:  # to a place not reached yet
                reached[there] = len(reached) + 1  # write the next number
                stack.append(there)  # and put it on top of the stack
            # a place reached already is passed by
        else:  # no road left from it
            stack.pop()  # take it off the stack, and step back
    return reached  # each number: the order the place was reached


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 the order that walk reached them.
    """
    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(list(piece))
    return pieces

how it scales

How many looks the walk makes on maps of 10 to 1,000 places, each map in one piece. nn on the plot is how many places.

Each mark across or up is ten times the one before. A line of places climbs one mark up for each mark across: ten times the places, about 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, about 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 depth-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. The place on top of the stack looks
along its next road, reached already or not, and a place with no road
left comes off the stack, which looks along nothing. The counts are the
same on any computer; only the time differs.
"""


def depth_first_search(roads, start):
    """Number the places in the order a deep walk from start reaches them.

    roads is a list of pairs of places, such as ("A", "B"), each road
    running both ways. Returns a dict, a table, of each place reached
    and its number, the start 1. 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):
    reached = {start: 1}  # write 1 at the start
    stack = [start]  # and put it on the stack
    looked = {}  # how many of each place's roads it has looked along
    while stack:  # while the stack is not empty
        here = stack[-1]  # the place on top
        k = looked.get(here, 0)  # how many it has looked along so far
        if k < len(near.get(here, [])):  # it has a road left
            looked[here] = k + 1
            there = near[here][k]  # follow its next road, in letter order
            if there not in reached:  # to a place not reached yet
                reached[there] = len(reached) + 1  # write the next number
                stack.append(there)  # and put it on top of the stack
            # a place reached already is passed by
        else:  # no road left from it
            stack.pop()  # take it off the stack, and step back
    return reached  # each number: the order the place was reached


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 the order that walk reached them.
    """
    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(list(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
    reached = {start: 1}
    stack = [start]
    looked = {}
    while stack:
        here = stack[-1]
        k = looked.get(here, 0)
        if k < len(near.get(here, [])):
            looked[here] = k + 1
            looks += 1
            there = near[here][k]
            if there not in reached:
                reached[there] = len(reached) + 1
                stack.append(there)
        else:
            stack.pop()
    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

This section's maps are in one piece, so every place is reached. On a map in pieces the walk looks only along its start's piece, so those are 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 a line and every pair joined. With 8 places, a line makes 14 looks, the town of eight 16, and every pair 56.

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) looks, each of the line's n−1n - 1 roads twicen(n−1)n(n - 1) looks, 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: Two numbers at each place: its number and how many of its roads it has looked along. A stack of at most nn places, each going on once (section 4's first question, line 1).

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

A1B2C2D2H1
A line of 5 places, 4 roads, the fifth named H as on the watch page. The number above each place is its degree, how many roads end there. They add to 8, so the walk makes 8 looks.
A4B4C4D4H4
The same 5 places, every pair joined, 10 roads. Each place has degree 4, so the walk makes 20 looks.
placesa lineevery pair
222
346
4612
5820
61030
81456
101890
1001989,900
1,0001,998999,000
Looks, the walk's own count. Ten times the places: about ten times the looks on a line, about a hundred times with every pair joined.

where the formula comes from

Each count above, worked out line by line. A reason names any line it uses, unless that is the line just before.

On a map in one piece with mm roads, why does the walk make 2m2m looks, and what does all its work cost?
  1. the move: on once, off once

    the line:
    each place reached goeson the stack once, andcomes off once\begin{gathered} \text{each place reached goes} \\ \text{on the stack once, and} \\ \text{comes off once} \end{gathered}

    why it is allowed: A place goes on when it is first reached, and a place reached already is passed by, so it goes on once. Each time a place is on top, it uses up one of its roads, or comes off if none is left. A map has only so many roads, so the stack empties, and each place that went on has come off.

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

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

    why it is allowed: Suppose a place is never reached. On a route from the start to it, take the first place not reached, C in the picture. The place before it, B, is reached, so by line 1 it comes off, and only with no road left. So it looked along the road to C, and C is reached after all. But we said C was not reached, so that cannot happen. So no place is missed.

  3. the move: each of its roads

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

    why it is allowed: It follows its roads in letter order, one each time it is on top, and never goes back to one. By line 1 it comes off, and only when none is left. 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}
    A2B3C3D1E1F2G3H1
    The town of eight with each place's degree above it. They add to 16.

    why it is allowed: LL is the looks. By lines 1 and 2 every place is on the stack 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
    roadfrom one endfrom the otherlooks
    A-BAB2
    A-EAE2
    B-CBC2
    B-FBF2
    C-DCD2
    C-GCG2
    F-GFG2
    G-HGH2
    all16
    The same 16 looks of the town, counted road by road instead of place by place.

    why it is allowed: By line 4, counted road by road. A road has two ends, and both are on the stack in turn, 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: open "where does this come from?" under this line. For the town of eight, 8 roads, 16 looks.

  7. the move: the queue's walk too

    the line:
    breadth-first search:2m looks too\begin{gathered} \text{breadth-first search:} \\ 2m \text{ looks too} \end{gathered}
    maptallest stacklongest queue
    a line of 5, from one end51
    the town of eight, from A53
    a loop of 8, drawn in section 6, from A82
    A joined to B, E and F, from A23
    The most places each walk keeps at once: the room it needs. The stack's count includes the place on top. The queue's count leaves out the place just taken, which has left it. Neither is always the smaller.

    why it is allowed: Its queue, places waiting in a line and taken oldest first, also takes each place once, and a place taken looks along each of its roads once. So lines 4 to 6 hold for it as well. For the town of eight, 16 looks each. What differs is how many places wait.

  8. the move: the books' letters

    the line:
    V is n, the places;E is m, the roads\begin{gathered} V \text{ is } n, \text{ the places;} \\ E \text{ is } m, \text{ the roads} \end{gathered}

    why it is allowed: From here the question is all the walk's work, places taken off as well as looks. Books write this with VV and EE. For the town of eight, VV is 8 and EE is 8.

  9. the move: count the places taken off too

    the line:
    V off and 2E looks:V+2E in all\begin{gathered} V \text{ off and } 2E \text{ looks:} \\ V + 2E \text{ in all} \end{gathered}
    the town of eightcount
    VV off8
    2E2E looks16
    V+2EV + 2E24
    V+EV + E16
    2V+2E2V + 2E32
    The town of eight. Its 8 places off and 16 looks make 24. That lies between V+EV + E, which is 16, and 2V+2E2V + 2E, which is 32.

    why it is allowed: Taking a place off is work too, though it looks along no road. Lines 1 and 2 take each place off once, and line 6 gives 2E2E looks.

  10. 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 9's total, and EE is not below 0. For the town of eight, 16 is at most 24.

  11. 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 9's total, and VV is not below 0. 2V+2E2V + 2E is twice V+EV + E. For the town, 24 is at most 32.

  12. the move: read the floor as a bound

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

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

  13. the move: read the ceiling as a bound

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

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

  14. 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 12 and 13 bound the places off and looks by the same growth, V+EV + E, on every map in one piece.

  15. the move: a new walk for each piece

    the line:
    every piece walked,any map: V offand 2E looks\begin{gathered} \text{every piece walked,} \\ \text{any map: } V \text{ off} \\ \text{and } 2E \text{ looks} \end{gathered}

    why it is allowed: A walk takes its own piece's places off once and looks along its roads twice, by lines 1 to 6. A new walk starts only at a place no walk has reached, and each road lies in one piece. For the map in two pieces, 8 off and 12 looks in all.

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}
    ABCDH
    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 section 4's 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)
    looksplaces051015200246810looksplaces051015200246810
    • 2n2n
    • KK, 2n−22n - 2
    • nn
    KK, 2n−22n - 2, between nn below and 2n2n above, from 2 places on. At 5 places, 5 is at most 8, and 8 is at most 10.

    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),the looks on the fewest roads\begin{gathered} K= 2(n - 1), \\ \text{the looks on the fewest roads} \end{gathered}
    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, now for what it means. Open "where does this come from?" under this line: nn places in one piece need at least n−1n - 1 roads. 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: The same fact as line 10: nn places in one piece need at least n−1n - 1 roads.

  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 section 4's first question the walk on such a map makes 2m2m looks, and by line 3 KK is 2(n−1)2(n - 1). So by line 12 no map in one piece costs less than KK.

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 section 4's 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}: open "where does this come from?" under this line. 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: split off half of n squared

    the line:
    W=n22+n(n−2)2W = \frac{n^2}{2} + \frac{n(n - 2)}{2}
    placesWWhalf of n2n^2the rest
    2220
    364.51.5
    41284
    52012.57.5
    WW split in two. The rest is never below 0 from 2 places on, since n−2n - 2 is not.

    why it is allowed: By line 5. Take half of n2n^2 from n2−nn^2 - n, and n(n−2)2\frac{n(n - 2)}{2} is left. For 4, 16 less 4 is 12, which is 8 plus 4.

  9. the move: a floor

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

    why it is allowed: Line 8 without its last part, which is not below 0 from 2 places on. For 4, 12 is at least 8.

  10. the move: read it as a bound

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

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

  11. the move: ceiling and floor together

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

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

  12. the move: no map has more roads

    the line:
    any map in one piece:m is at most n(n−1)2\begin{gathered} \text{any map 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. So no map has more roads than line 3's.

  13. the move: double both

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

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

  14. the move: compare with every pair

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

    why it is allowed: By section 4's first question the walk on such a map makes 2m2m looks, and by line 4 WW is n(n−1)n(n - 1). So by line 13 no map 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

count it yourself

Count every look as the walk crosses the line A, B, C, D, H from A, drawn in section 3. On the watch page you type this map as A-B, B-C, C-D, D-H; A. The A after the semicolon is the start. Nothing comes off until the far end, when all 5 are on the stack. Then all 5 come off: 4 step back to the place below, and the last, A, empties the stack. Each step below also shows the stack, bottom first.

A-B, B-C, C-D, D-H; A, every step written down
stepthe stack, bottom firstwhat happensroads looked along
1AStart at A. It is the first place reached, so write 1 there and put it on the stack.A0
2A, BB has not been reached yet, so follow the road from A to it. B is place number 2 to be reached: write 2 there, and put B on top of the stack.A, B1
3A, BA has been reached already, so pass it by and stay at B.A, B2
4A, B, CC has not been reached yet, so follow the road from B to it. C is place number 3 to be reached: write 3 there, and put C on top of the stack.A, B, C3
5A, B, CB has been reached already, so pass it by and stay at C.A, B, C4
6A, B, C, DD has not been reached yet, so follow the road from C to it. D is place number 4 to be reached: write 4 there, and put D on top of the stack.A, B, C, D5
7A, B, C, DC has been reached already, so pass it by and stay at D.A, B, C, D6
8A, B, C, D, HH has not been reached yet, so follow the road from D to it. H is place number 5 to be reached: write 5 there, and put H on top of the stack.A, B, C, D, H7
9A, B, C, D, HD has been reached already, so pass it by and stay at H.A, B, C, D, H8
10A, B, C, DEvery road from H has been looked along, so take H off the stack and step back to D.A, B, C, D8
11A, B, CEvery road from D has been looked along, so take D off the stack and step back to C.A, B, C8
12A, BEvery road from C has been looked along, so take C off the stack and step back to B.A, B8
13AEvery road from B has been looked along, so take B off the stack and step back to A.A8
14Every road from A has been looked along, so take A off the stack. The stack is now empty.8
15Done. 5 of the 5 places can be reached, and the numbers give the order they were reached.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

Python itself walks deep, and so does a widely used library for networks.

  • Python's os.walk

    os.walk goes through every folder inside a folder, and the folders inside those. It keeps a stack of folders still to visit, and takes the newest next, so it finishes one folder's insides before the next folder.

    source: Python's documentation, os.walk (opens in a new tab); Python's own code, Lib/os.py, its walk

  • Python's graphlib

    graphlib orders tasks when some need others first. If two tasks need each other, no order exists, and it finds that cycle by walking deep. Its links run one way, from a task to the tasks that need it. A link that leads back to a task still on its stack closes a cycle, as the third picture below shows. It tries every task in turn, as every_piece in section 1 tries every place.

    source: Python's documentation, graphlib (opens in a new tab); Python's own code, Lib/graphlib.py, its TopologicalSorter._find_cycle

  • networkx's deep order

    networkx is a library for studying networks of things. Hand it a map and a place to begin, and it can give back the places in this page's number order, if the roads are listed in letter order.

    source: the networkx source, depth_first_search.py (opens in a new tab), its dfs_preorder_nodes

A1B2C3D4E8F7G6H5
Deep is not near. On this loop the walk from A goes all the way round, drawn heavy. Each place shows its letter and its number. E gets number 8, at the end of 7 roads, though A-E is 1 road.
placenumberroads along the walk's routefewest roads
A100
B211
C322
D433
H544
G653
F762
E871
The loop from A. A place's number says when the walk reached it, not how near it is.
ABC
Three tasks, each needed by the next, on one-way roads. The walk from A stacks A, B, C. Then C's road leads back to A, still on the stack, so A, B, C and back to A is a cycle.

what is used instead

To find the fewest roads, use breadth-first search, whose queue takes the oldest place next. The walk can also be written as a function, a named piece of a program, that starts itself for each new place. Each start is a call, and Python keeps the calls as its own stack. That is shorter, but Python stops at 1,000 calls deep unless you change its limit. So a line of 2,000 places stops with an error, RecursionError. A stack of your own, as here, goes on.

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 placelooks, in one piece
depth-first searcha stack, newest on topone road from the newest, back when none is leftthe order reached2m2m
breadth-first searcha queue, oldest firstevery road of the oldestfewest roads from the start2m2m
The two walks take a different place next and go a different way. On a map in one piece both make 2m2m looks, by section 4's first question, lines 6 and 7.
A1B2C3D4E8F6G5H7
Depth-first search on the town of eight from A. Each place shows its letter and the order it was found. It goes deep and finds E last.
A1B2C4D6E3F5G7H8
Breadth-first search on the same town. It spreads out, and finds E third, one road from A.