Watch Tower of Hanoi solve itself move by move with recursion. Worked example with 3 disks, then try up to 7, and see why moves double with each disk.
About this algorithm
Tower of Hanoi moves a stack of disks from one peg to another, one disk at a time, never putting a larger disk on a smaller one, with a third peg to park disks on. It is the classic first lesson in recursion: the biggest disk can only move once every disk above it is out of the way, and moving those is the same puzzle with one disk fewer.
Study Hanoi to learn how a recursive function trusts a call on a smaller input to do its job. It shares this page with three backtracking puzzles, but it is a different kind of problem: nothing is guessed and nothing is undone, because the best sequence of moves is fixed in advance and every call does useful work. N-Queens, Sudoku and Rat in a Maze search by making a choice and taking it back when it fails. Pick Hanoi to see plain divide and conquer recursion and the call stack it builds; pick one of the other three to see backtracking.
Call them from, to and spare. For the whole puzzle on this page, from is A, to is C and spare is B.
Recursively move the top n - 1 disks from the from peg to the spare peg, using the to peg as their spare. The page calls this act 1.
The largest disk is now alone and the to peg is empty, so move it across in one move. This is act 2.
Recursively move the same n - 1 disks from the spare peg onto the to peg, with the from peg as spare. This is act 3. A call asked to move 0 disks returns at once, which ends the recursion.
The page starts with 3 disks on peg A and the goal is peg C. Act 1 moves the top 2 disks from A to B: disk 1 from A to C, disk 2 from A to B, disk 1 from C to B. Act 2 moves disk 3 from A to C. Act 3 moves the 2 disks from B to C: disk 1 from B to A, disk 2 from B to C, disk 1 from A to C. That is 7 moves, and the call stack rail next to the pegs never holds more than 3 open calls. Disk 1, the smallest, moves on every odd move: 1, 3, 5 and 7. Push the slider to 7 disks and the same plan takes 127 moves.
Moving n disks takes the moves for n - 1 disks twice, plus one: M(n) = 2 × M(n - 1) + 1, with M(0) = 0. That gives 1, 3, 7, 15, 31, so M(n) = 2^n - 1. No method does better: the largest disk must move at least once, and when it does, all the others have to be stacked on the third peg. At one move per second, 64 disks would take about 585 billion years.
Time: the puzzle needs exactly 2^n - 1 moves and the function makes one move per call that has a disk, so each extra disk doubles the work. Space: the recursion is at most n calls deep, one open call per disk size, and the pegs hold the n disks.