How does the recursive solution to the Tower of Hanoi work, and what does it do in each step?
To move n discs from one peg to another, using a third peg as the spare, you do three things. Move the top n minus one discs from the source to the spare peg. Move the single largest disc from the source to the target peg. Move the n minus one discs from the spare peg onto the target peg, on top of the largest one.
def hanoi(count, source, target, spare, moves=None):
if moves is None:
moves = []
if count == 0:
return moves
hanoi(count - 1, source, spare, target, moves)
moves.append((source, target))
hanoi(count - 1, spare, target, source, moves)
return moves
for move in hanoi(3, "A", "C", "B"):
print(move)The output is three moves: A to B, A to C and B to C. That is the classic seven-move solution for three discs, printed as the three top-level moves with the recursive steps flattened into the list.
The mechanism is that the top n minus one discs have to be out of the way before the largest disc can move, and they must then be stacked back on top of it. Each of those two transfers is itself a Tower of Hanoi problem with one fewer disc, which is why the function calls itself twice with the peg roles permuted. The base case of zero discs does nothing, which terminates the recursion.
The trade-off to name is the stack depth. The recursion nests n levels deep, so the space complexity is O of n, and the time is dominated by the number of moves, which is exponential. For thirty discs that is over a billion moves, so the practical version of this problem asks for the count rather than the moves, or asks for the moves in a compressed or grouped form. The three-peg structure is also what makes it a good recursion example: it is one of the simplest problems where the recursive decomposition is genuinely easier to see than the iterative version.