Depth-first search
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.
| step | what happens | the stack, bottom first |
|---|---|---|
| 1 | write 1 at A | A |
| 2 | A looks along A-B: B not reached, write 2 | A, B |
| 3 | B looks along B-A: A reached, pass by | A, B |
| 4 | B looks along B-C: C not reached, write 3 | A, B, C |
| 5 | C looks along C-B: B reached, pass by | A, B, C |
| 6 | C has no road left: off, step back to B | A, B |
| 7 | B has no road left: off, step back to A | A |
| 8 | A has no road left: off | empty |
step 1 of 26
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.
step 6 of 26
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
step 7 of 26
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
step 8 of 26
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
step 11 of 26
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
step 15 of 26
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
step 22 of 26
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
step 26 of 26
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- write 1 at the start, and put it on the stackPython lines 23 and 24
- 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
- to a place not reached yet: write the next number there, and put it on top of the stackPython lines 32, 33 and 34
- to a place reached already: pass it byPython line 35
- no road left from it: take it off the stack, and step backPython lines 36 and 37
- 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. 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
, 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
| roads looked along | time | |
|---|---|---|
| 1,000 | 999,000 | about 999 microseconds |
| 100,000 | 9,999,900,000 | about 10 seconds |
| 10,000,000 | 99,999,990,000,000 | about 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.
| besta line, the fewest roads that join the places in one piece | worstevery pair joined, the most roads | |
|---|---|---|
| roads looked along | looks, each of the line's roads twice | looks, each of the roads twice |
| how the roads looked along grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: Two numbers at each place: its number and how many of its roads it has looked along. A stack of at most 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.
| places | a line | every pair |
|---|---|---|
| 2 | 2 | 2 |
| 3 | 4 | 6 |
| 4 | 6 | 12 |
| 5 | 8 | 20 |
| 6 | 10 | 30 |
| 8 | 14 | 56 |
| 10 | 18 | 90 |
| 100 | 198 | 9,900 |
| 1,000 | 1,998 | 999,000 |
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.
the move: on once, off once
the line: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.
the move: in one piece, every place reached
the line: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.
guess it, thenthe move: each of its roads
the line:place roads it looks along A 2 B 3 C 3 D 1 G 3 F 2 H 1 E 1 all 16 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.
guess it, thenthe move: add up the degrees
the line:The town of eight with each place's degree above it. They add to 16. why it is allowed: is the looks. By lines 1 and 2 every place is on the stack once, and by line 3 each looks along its degree.
guess it, thenthe move: count each road at both ends
the line:road from one end from the other looks A-B A B 2 A-E A E 2 B-C B C 2 B-F B F 2 C-D C D 2 C-G C G 2 F-G F G 2 G-H G H 2 all 16 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: twos, the dots standing for those not written.
guess it, thenthe move: add the twos
the line:where does this come from?
question 1 of the page graphs and their wordsA map has roads. What do the degrees of its places add to? the move: count each road at both ends
the line:The map of 6 places, each place's degree written above it. why it is allowed: Let be the degrees added up. Every road has two ends, and it counts once at the place on each end, 2 in all. So roads give twos, the dots standing for the twos not written. For 7 roads, 7 twos.
the move: add the twos
the line:why it is allowed: twos make twice .
the move: read it
the line:place degree A 2 B 3 C 2 D 2 E 3 F 2 all 14 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.
the move: odd degrees come in pairs
the line:why it is allowed: Line 2's total is twice , 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.
why it is allowed: twos make twice . 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.
guess it, thenthe move: the queue's walk too
the line:map tallest stack longest queue a line of 5, from one end 5 1 the town of eight, from A 5 3 a loop of 8, drawn in section 6, from A 8 2 A joined to B, E and F, from A 2 3 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.
guess it, thenthe move: the books' letters
the line: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 and . For the town of eight, is 8 and is 8.
guess it, thenthe move: count the places taken off too
the line:the town of eight count off 8 looks 16 24 16 32 The town of eight. Its 8 places off and 16 looks make 24. That lies between , which is 16, and , 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 looks.
guess it, thenthe move: a floor
the line:why it is allowed: Take away from line 9's total, and is not below 0. For the town of eight, 16 is at most 24.
guess it, thenthe move: a ceiling
the line:why it is allowed: Add to line 9's total, and is not below 0. is twice . For the town, 24 is at most 32.
guess it, thenthe move: read the floor as a bound
the line:why it is allowed: By line 10, with the fixed multiple 1, on every map in one piece.
guess it, thenthe move: read the ceiling as a bound
the line:why it is allowed: By line 11, with the fixed multiple 2, on every map in one piece.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 12 and 13 bound the places off and looks by the same growth, , on every map in one piece.
guess it, thenthe move: a new walk for each piece
the line: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.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: a line's roads
the line: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.
the move: twice each road
the line:why it is allowed: is the looks on a line. By section 4's first question each road is looked along twice, and by line 1 there are roads.
guess it, thenthe move: add the twos
the line:why it is allowed: twos make twice . For 5 places, 8.
guess it, thenthe move: open the bracket
the line:why it is allowed: Twice , less twice 1. For 5, 10 less 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4, without the 2 taken away.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4, is plus , which is not below 0 from 2 places on. For 5, 8 is at least 5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, with the fixed multiple 1, from 2 places on.
guess it, thenthe move: ceiling and floor together
the line:- ,
, , between below and 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 by the same growth, .
guess it, thenthe move: a line has the fewest roads
the line:where does this come from?
question 3 of the page graphs and their words places in one piece, on two-way roads. How few roads can join them? the move: start with no roads
the line:why it is allowed: With no roads, each place is a piece on its own.
the move: a road joins two pieces at most
the line: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.
the move: count the pieces left
the line:roads laid road pieces 0 none yet 7 1 A to B 6 2 A to C 5 3 B to D 4 4 C to D 4 5 E to F 3 6 E to G 2 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 be how many are laid. Start at pieces and take off at most 1 for each road.
the move: ask for one piece
the line:why it is allowed: Line 3's pieces can be 1 only if is 1 or less.
the move: turn it round
the line:why it is allowed: When is at most 1, falls short of by at most 1. So fewer than 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.
the move: a line of places is enough
the line: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 roads, and every place reaches the first.
the move: the fewest
the line:why it is allowed: Let be the fewest roads. Line 5 says no fewer than will do, and line 6 that do.
why it is allowed: Line 3 again, now for what it means. Open "where does this come from?" under this line: places in one piece need at least roads. By line 1 a line has exactly , so it has the fewest.
guess it, thenthe move: any map in one piece
the line:why it is allowed: The same fact as line 10: places in one piece need at least roads.
guess it, thenthe move: double both
the line:why it is allowed: Twice each side of line 11.
guess it, thenthe move: compare with the line
the line:why it is allowed: By section 4's first question the walk on such a map makes looks, and by line 3 is . So by line 12 no map in one piece costs less than .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the roads place by place
the line: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 others, the next adds one fewer new road, and the last adds none.
the move: twice each road
the line:why it is allowed: is the looks with every pair joined. By section 4's first question, twice line 1's roads.
guess it, thenthe move: add up 1 to n - 1
the line:where does this come from?
question 2 of the page graphs and their words places, every two joined by a road. How many roads? the move: count place by place
the line: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 be the roads, for 2 places or more. List the places. The first has roads to the 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.
the move: use adding up 1 to n
the line:place new roads A 4 B 3 C 2 D 1 E 0 all 10 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 Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: Read from right to left, line 1 is 1 + 2 + up to . 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 . One more than it is , so is times , halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.
the move: one way, each pair holds two
the line:why it is allowed: Let be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.
the move: double line 2
the line:why it is allowed: Line 3 says is , and twice line 2 is . For 5 places, 20.
the move: read it
the line: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.
why it is allowed: The roads add to : open "where does this come from?" under this line. For 4 places, 4 times 3 over 2 is 6.
guess it, thenthe move: twice a half is 1
the line:why it is allowed: By line 3, the 2 and the half cancel. For 4, 12.
guess it, thenthe move: open the bracket
the line:why it is allowed: times , less times 1. For 4, 16 less 4.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 5, without the taken away.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: split off half of n squared
the line:places half of the rest 2 2 2 0 3 6 4.5 1.5 4 12 8 4 5 20 12.5 7.5 split in two. The rest is never below 0 from 2 places on, since is not. why it is allowed: By line 5. Take half of from , and is left. For 4, 16 less 4 is 12, which is 8 plus 4.
guess it, thenthe move: a floor
the line: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.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, with the fixed multiple a half, from 2 places on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 7 and 10 bound by the same growth, .
guess it, thenthe move: no map has more roads
the line: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.
guess it, thenthe move: double both
the line:why it is allowed: Twice each side of line 12.
guess it, thenthe move: compare with every pair
the line:why it is allowed: By section 4's first question the walk on such a map makes looks, and by line 4 is . So by line 13 no map in one piece costs more than .
guess it, then
try it with a small : at , line 2 gives , 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.
| step | the stack, bottom first | what happens | roads looked along |
|---|---|---|---|
| 1 | A | Start at A. It is the first place reached, so write 1 there and put it on the stack.A | 0 |
| 2 | A, B | B 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, B | 1 |
| 3 | A, B | A has been reached already, so pass it by and stay at B.A, B | 2 |
| 4 | A, B, C | C 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, C | 3 |
| 5 | A, B, C | B has been reached already, so pass it by and stay at C.A, B, C | 4 |
| 6 | A, B, C, D | 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.A, B, C, D | 5 |
| 7 | A, B, C, D | C has been reached already, so pass it by and stay at D.A, B, C, D | 6 |
| 8 | A, B, C, D, H | H 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, H | 7 |
| 9 | A, B, C, D, H | D has been reached already, so pass it by and stay at H.A, B, C, D, H | 8 |
| 10 | A, B, C, D | Every road from H has been looked along, so take H off the stack and step back to D.A, B, C, D | 8 |
| 11 | A, B, C | Every road from D has been looked along, so take D off the stack and step back to C.A, B, C | 8 |
| 12 | A, B | Every road from C has been looked along, so take C off the stack and step back to B.A, B | 8 |
| 13 | A | Every road from B has been looked along, so take B off the stack and step back to A.A | 8 |
| 14 | Every road from A has been looked along, so take A off the stack. The stack is now empty. | 8 | |
| 15 | Done. 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, , gives at : 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
| place | number | roads along the walk's route | fewest roads |
|---|---|---|---|
| A | 1 | 0 | 0 |
| B | 2 | 1 | 1 |
| C | 3 | 2 | 2 |
| D | 4 | 3 | 3 |
| H | 5 | 4 | 4 |
| G | 6 | 5 | 3 |
| F | 7 | 6 | 2 |
| E | 8 | 7 | 1 |
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.
| walk | keeps its places in | what it does next | writes at each place | looks, in one piece |
|---|---|---|---|---|
| depth-first search | a stack, newest on top | one road from the newest, back when none is left | the order reached | |
| breadth-first search | a queue, oldest first | every road of the oldest | fewest roads from the start |