Loading…
Loading…
The classic recursion puzzle: move a stack of disks to another peg, never placing a larger disk on a smaller one. Solves in 2ⁿ − 1 moves.
Move 3 disks from A to C, one at a time.
The three Tower of Hanoi pegs
1void hanoi(int n, char from, char to, char aux) {2 if (n == 1) { move(from, to); return; } // base case: one disk3 hanoi(n-1, from, aux, to); // move top n-1 to aux4 move(from, to); // move the largest disk5 hanoi(n-1, aux, to, from); // move n-1 onto target6}7 8void move(char from, char to) { // move top disk: from → to9 System.out.println(from + " -> " + to);10}