Back to problems
COMP2521
Recursion: Tower of Hanoi
Recursion: Tower of Hanoi
Three pegs A, B, C; peg A holds n disks stacked largest-at-bottom. Move them all from A to C: only one disk at a time, and a larger disk may never sit on a smaller one. Print every move, recursively.
The essence of recursion — split "move n" into two "move n−1" subproblems:
- Move the top
n-1disks fromfromtovia(usingtoas spare); - Move the largest disk from
fromdirectly toto(print this move); - Move those
n-1disks fromviatoto(usingfromas spare).
Base case: when n == 0 there is nothing to move (just return). Complete hanoi.
Pitfalls: (1) omitting then == 0base causes infinite recursion / stack overflow. (2) Pass the correct spare peg to each recursive call — first usestoas spare, third usesfrom; swapping them breaks the rule. (3) The printed move goes between the two recursive calls.
Input
- One line: integer
n(0 ≤ n ≤ 12), the number of disks.
Output
- One move per line, formatted
X -> Y(move from peg X to peg Y).ndisks take exactly2^n − 1moves;n = 0prints nothing.
Example: input 2 -> three lines A -> B / A -> C / B -> C.
Samples
stdin
1
expected
A -> C
stdin
3
expected
A -> C A -> B C -> B A -> C B -> A B -> C A -> C
c-dcc
14