Organizing Data The Towers of Hanoi In this

  • Slides: 13
Download presentation
Organizing Data: The Towers of Hanoi In this puzzle, the player begins with n

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

Towers of Hanoi Puzzle 2

Towers of Hanoi Puzzle 2

Towers of Hanoi Puzzle 3

Towers of Hanoi Puzzle 3

Towers of Hanoi Puzzle 4

Towers of Hanoi Puzzle 4

Towers of Hanoi Puzzle 5

Towers of Hanoi Puzzle 5

Towers of Hanoi Puzzle 6

Towers of Hanoi Puzzle 6

Towers of Hanoi Puzzle 7

Towers of Hanoi Puzzle 7

Towers of Hanoi Puzzle 8

Towers of Hanoi Puzzle 8

The Towers of Hanoi • Pseudocode solution solve. Towers(count, source, destination, spare) if (count

The Towers of Hanoi • Pseudocode solution solve. Towers(count, source, destination, spare) if (count is 1) Move a disk directly from source to destination else { solve. Towers(count-1, source, spare, destination) solve. Towers(1, source, destination, spare) solve. Towers(count-1, spare, destination, source) } //end if 9

The Cost of Towers of Hanoi • Solution to the Towers of Hanoi problem

The Cost of Towers of Hanoi • Solution to the Towers of Hanoi problem solve. Towers(count, source, destination, spare) if (count is 1) Move a disk directly from source to destination else { solve. Towers(count-1, source, spare, destination) solve. Towers(1, source, destination, spare) solve. Towers(count-1, spare, destination, source) }

The Cost of Towers of Hanoi • With N disks, how many moves does

The Cost of Towers of Hanoi • With N disks, how many moves does solve. Towers 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(N – 1)

The Cost of Towers of Hanoi • Recurrence relation for the number of moves

The Cost of Towers of Hanoi • Recurrence relation for the number of moves that solve. Towers 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-formula is more satisfactory – You

The Cost of Towers of Hanoi • A closed-formula is more satisfactory – You can substitute any given value for N and obtain the number of moves made – moves(N ) = 2 N – 1, for all N ≥ 1 – Induction on N can prove this