Tower of Hanoi in Java
Problem
The Tower of Hanoi puzzle moves a stack of disks from one peg to another, one disk at a time, using a third peg to help, under the rule that a larger disk can never sit on top of a smaller one.
Given a number of disks, move them all from a source peg to a destination peg using an auxiliary peg, printing every individual move.
Java Program
public class TowerOfHanoi {
static void hanoi(int n, char from, char aux, char to) {
if (n == 0) return; // base case: no disks to move
hanoi(n - 1, from, to, aux); // move n-1 disks out of the way
System.out.println("Move disk " + n + " from " + from + " to " + to);
hanoi(n - 1, aux, from, to); // move those n-1 disks onto the target
}
public static void main(String[] args) {
int n = 3;
hanoi(n, 'A', 'B', 'C');
}
}Output
Core Logic
Moving the top n - 1 disks out of the way first, then moving the single largest disk, then moving those n - 1 disks on top of it, solves the whole stack by reducing it to two smaller versions of the same puzzle.
- 1
hanoi(n, from, aux, to)movesndisks from thefrompeg to thetopeg, usingauxas the spare. - 2The base case
if (n == 0) return;does nothing, since there's no disk to move. - 3
hanoi(n - 1, from, to, aux)shifts the smaller disks onto the auxiliary peg first, clearing the way for the largest disk. - 4After printing the move of disk
nitself fromfromtoto,hanoi(n - 1, aux, from, to)moves those same smaller disks from the auxiliary peg onto the destination, on top of the disk that just landed.
A to C — right in the middle of the sequence.Key Point: The roles of the three pegs swap between recursive calls — the auxiliary peg for one call becomes the source or destination for the next — which is what lets the same three-parameter method solve every sub-problem without extra bookkeeping.
Why: Each additional disk doubles the number of moves needed — 2ⁿ - 1 in total — while the recursion only ever nests n calls deep at once.