{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

T06_stack

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

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

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 first Tower 1 Tower 2 Tower 3 Figure 5.4 Towers of Hanoi

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

View Full Document
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 "
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

{[ snackBarMessage ]}

What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern