T06_stack - ≪ x ≪ " to top of tower " ≪ y...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
COMP 152, Spring 2010 Tower of Hanoi 1 Tutorial #6 Tower of Hanoi Given n disks and three towers labeled as tower 1, tower 2, and tower 3. The disks are initially stacked on tower 1 in decreasing order of size from bottom to top Move the disks to tower 2, using tower 3 for intermediate storage. Move one disk at a time, such that no disk is ever on top of a smaller one Try to do n = 2 , 3 , 4 Frst Tower 1 Tower 2 Tower 3 Figure 5.4 Towers of Hanoi
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
COMP 152, Spring 2010 Tower of Hanoi 2 Solutions: Tower of Hanoi Problem void TowersOfHanoi( int n, int x, int y, int z) { // Move the top n disks from tower x //to tower y. // Use tower z for intermediate storage. if (n > 0) { TowersOfHanoi(n-1, x, z, y); cout "Move top disk from tower "
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ≪ x ≪ " to top of tower " ≪ y ≪ endl; TowersOfHanoi(n-1, z, y, x); } } Call TowersOfHanoi( n, 1, 2, 3 ) There is an animation on Tower of Hanoi in the course webpage under the “many applets” link. COMP 152, Spring 2010 Tower of Hanoi 3 Complexity The time taken is proportional to the number of lines of output generated, and the number of lines output is equal to the number of disk moves performed. moves ( n ) =        n = 0 2 moves ( n − 1) + 1 n > This yields move ( n ) = 2 n − 1 , i.e., the total number of moves is exponential — which takes very long time if n is large!...
View Full Document

This note was uploaded on 08/25/2010 for the course COMP COMP152 taught by Professor D.y.yeung during the Spring '10 term at HKUST.

Page1 / 3

T06_stack - ≪ x ≪ " to top of tower " ≪ y...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online