Breadth-first search
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.
| roads from A | places |
|---|---|
| 0 | A |
| 1 | B, E |
| 2 | C, F |
| 3 | D, G |
| 4 | H |
step 1 of 34
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.
step 4 of 34
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
step 9 of 34
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
step 12 of 34
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
step 17 of 34
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
step 21 of 34
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
step 29 of 34
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
step 34 of 34
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- write 0 at the start, and put it in the queuePython lines 26 and 27
- while the queue is not empty, take the place at its frontPython lines 28 and 29
- look along each road from it, in letter orderPython lines 20, 21 and 30
- a place not found yet: write one more than here, and put it at the back of the queuePython lines 31, 32 and 33
- a place found already: pass it byPython line 34
- 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
, 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 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.
| besta line, the fewest roads that join the places in one piece | worstevery pair joined, the most roads | |
|---|---|---|
| roads looked along | , each of the line's roads twice | , each of the roads twice |
| how the roads looked along grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: a number at each place and a queue of at most 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.
| 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. Each reason names the line it uses.
the move: joins once, taken once
the line: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.
the move: in one piece, every place found
the line: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.
guess it, thenthe move: each of its roads
the line:place taken roads it looks along A 2 B 3 E 1 C 3 F 2 D 1 G 3 H 1 all 16 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.
guess it, thenthe move: add up the degrees
the line:why it is allowed: is the roads looked along. By lines 1 and 2 every place is taken once, and by line 3 each looks along its degree.
guess it, thenthe move: count each road at both ends
the line:why it is allowed: By line 4. A road has two ends, and both are taken, 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, in this line's fold. For the town of eight, 8 roads, 16 looks.
guess it, thenthe move: count the takes too
the line:the town of eight count takes 8 looks 16 24 16 32 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 for the places, here , and for the roads, here . Lines 1 and 2 take each place once, takes, and line 6 gives looks.
guess it, thenthe move: a floor
the line:why it is allowed: Take away from line 7'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 7'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 8, 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 9, 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 10 and 11 bound the takes and looks by the same growth, , on every map in one piece.
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 the 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: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. This line's fold shows that places in one piece need at least roads, and 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: By line 10's fold.
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 the first question it looks along roads, and by line 3 is . So by line 12 no map in one piece costs less than a line.
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 the 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 , in this line's fold. 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: a floor
the line:why it is allowed: By line 5. For 4, 16 less 4 is 12, and half of 16 is 8. In general, less half of is half of less , not below 0 from 2 places on.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, 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 9 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. With every pair joined, any two places already have their road. So no map of places has more than line 3's . For 4 places, 6.
guess it, thenthe move: double both
the line:why it is allowed: Twice each side of line 11.
guess it, thenthe move: twice a half is 1
the line:a map of 4 places roads looks a line, A-B-C-D 3 6 a loop, A-B-C-D and back to A 4 8 every pair 6 12 Maps of 4 places in one piece. Every pair has the most roads, so the most looks, at 12. why it is allowed: By line 12, the 2 and the half cancel, as in line 4.
guess it, thenthe move: compare with every pair
the line:why it is allowed: By the first question the walk on such a map looks along roads, and by line 4 is . So by line 13 no map of places 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
the move: a row for each place
the line: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. places looks on a line cells checked in a grid 5 8 25 10 18 100 100 198 10,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: is the cells checked. By the first question's lines 1 and 2 each of the places is taken once. Its row has a cell for every place, and it checks them all.
the move: add them up
the line:why it is allowed: added times is times . For a line of 5 places, 25 cells, against 8 looks.
guess it, then
try it with a small : at , line 1 gives , 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.
| step | the queue, front first | what happens | roads looked along |
|---|---|---|---|
| 1 | A | Start at A. It is 0 roads from itself, so write 0 there and put it in the queue.A | 0 |
| 2 | Take A from the front of the queue. It is 0 roads from the start. | 0 | |
| 3 | B | B 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.B | 1 |
| 4 | B | Every road from A has been looked along, so A is done.B | 1 |
| 5 | Take B from the front of the queue. It is one road from the start. | 1 | |
| 6 | A has been found already, by no more roads than going through B would take, so pass it by. | 2 | |
| 7 | C | C 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.C | 3 |
| 8 | C | Every road from B has been looked along, so B is done.C | 3 |
| 9 | Take C from the front of the queue. It is 2 roads from the start. | 3 | |
| 10 | B has been found already, by no more roads than going through C would take, so pass it by. | 4 | |
| 11 | D | D 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.D | 5 |
| 12 | D | Every road from C has been looked along, so C is done.D | 5 |
| 13 | Take D from the front of the queue. It is 3 roads from the start. | 5 | |
| 14 | C has been found already, by no more roads than going through D would take, so pass it by. | 6 | |
| 15 | H | H 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.H | 7 |
| 16 | H | Every road from D has been looked along, so D is done.H | 7 |
| 17 | Take H from the front of the queue. It is 4 roads from the start. | 7 | |
| 18 | D has been found already, by no more roads than going through H would take, so pass it by. | 8 | |
| 19 | Every road from H has been looked along, so H is done. | 8 | |
| 20 | Done. 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, , gives at : 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)
| place | reached from | roads from A |
|---|---|---|
| A | none | 0 |
| B | A | 1 |
| E | A | 1 |
| C | B | 2 |
| F | B | 2 |
| D | C | 3 |
| G | C | 3 |
| H | G | 4 |
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.
| walk | keeps its places in | what it does next | writes at each place | roads looked along, in one piece |
|---|---|---|---|---|
| breadth-first search | a queue, oldest first | every road of the oldest | fewest roads from the start | |
| depth-first search | a stack, newest on top | one road from the newest, back when none is left | the order reached |
| found | breadth-first search | depth-first search |
|---|---|---|
| 1st | A | A |
| 2nd | B | B |
| 3rd | E | C |
| 4th | C | D |
| 5th | F | G |
| 6th | D | F |
| 7th | G | H |
| 8th | H | E |