Download presentation
Presentation is loading. Please wait.
Published byCatherine McGee Modified over 9 years ago
1
Recursion
2
Hanoi Tower Legend: Inside a Vietnamese temple there are three rods (labeled as r 1, r 2, and r 3 ), surrounded by n golden disks of different sizes. The monks of Hanoi wants to move these disks from r 1 to r 3 such that: at each step, take the upper disk of one rod and place it to the top of another rod no bigger disk can be placed on top of a smaller disk
3
Input and output format Input: A single integer n in [1, 20] Output: The steps to move the disks from r 1 to r 3 ; in the format of r i -> r j 3 r1 -> r3 r1 -> r2 r3 -> r1 r1 -> r3 r2 -> r1 r2 -> r3 r1 -> r3
4
Recursion Can we solve the problem by solving some smaller problems? To move n disks from r 1 to r 3 1.move n-1 disks from r 1 to r 2 2.move 1 disks from r 1 to r 3 3.move n-1 disks from r 2 to r 3 r1r1 r2r2 r3r3
5
Implementation Let hanoi( int n, int i, int j, int z ) be a function that will move n disks from rod i to rod j using rod k as the middle rod. void hanoi( int n, int i, int j, int k ){ if( n==1 ){ cout r" << j << endl; return; } hanoi( n-1, i, k, j ); hanoi( 1, i, j, k ); hanoi( n-1, k, j, i ); } int main(){ int n; cin >> n; hanoi( n ); return 0; }
6
How many moves are there? Let T(n) be the number of steps to move n disks T(1) = 1 T(n)= 2 T(n-1) + 1 = 4 T(n-2) + 2 + 1 =... = 2 n-1 T(1)+ 2 n-2 +... + 1 = 2 n - 1 The running time is also Θ(2 n ) = exponential time Very slow But it is optimal already (prove by M.I. on n)
7
Other recursion problems http://net.pku.edu.cn/~course/cs101/2007/book2/pp_list.txt Look for easy problems first POJ 1920
8
POJ 2386 Lake counting
11
POJ 2227
12
Topological sort
14
Summary We have seen some examples on recursion. ◦ Hanoi tower ◦ Reverse of hanoi tower Flood fill is a recursive method to identify connected region. ◦ Running time = size of the region We can order a partial ordered set by topological sort ◦ Running time = number of edges Exercises: UVA 900, 254, 699, 10940, 527, 572, 657, 11110, 10305, 11686, 200
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.