150 likes | 185 Views
Organizing Data: The Towers of Hanoi.
E N D
Organizing Data:The Towers of Hanoi In this puzzle, the player begins with n disks of decreasing diameter placed one on top of the other on one of three pegs of the game board. The player must move the disks from peg to peg, using each of the three pegs, until the entire tower is moved from the starting peg to one of the others. The only rule governing the movement of the disks is that in each move a disk of larger diameter must never be placed on top of one of smaller diameter 1
The Towers of Hanoi Pseudocode solution solveTowers(count, source, destination, spare) if (count is 1) Move a disk directly from source to destination else { solveTowers(count-1, source, spare, destination) solveTowers(1, source, destination, spare) solveTowers(count-1, spare, destination, source) } //end if 9
The Cost of Towers of Hanoi • Solution to the Towers of Hanoi problem solveTowers(count, source, destination, spare) if (count is 1) Move a disk directly from source to destination else { solveTowers(count-1, source, spare, destination) solveTowers(1, source, destination, spare) solveTowers(count-1, spare, destination, source) }
The Cost of Towers of Hanoi • With N disks, how many moves does solveTowers make? • Let moves(N) be the number of moves made starting with N disks • When N = 1 • moves(1)= 1 • When N > 1 • moves(N)= moves(N–1) + moves(1)+ moves(N–1)
The Cost of Towers of Hanoi • Recurrence relation for the number of moves that solveTowers requires for N disks • moves(1) = 1 • moves(N)= 2 * moves(N–1)+ 1 if N > 1
The Cost of Towers of Hanoi • A closed-form formula is more satisfactory • You can substitute any given value for N and obtain the number of moves made • moves(N)= 2N – 1, for all N≥ 1 • Induction on N can prove this