Recursion. Hanoi Tower Legend: Inside a Vietnamese temple there are three rods (labeled as r 1, r 2,...
-
Upload
catherine-mcgee -
Category
Documents
-
view
214 -
download
0
Transcript of Recursion. Hanoi Tower Legend: Inside a Vietnamese temple there are three rods (labeled as r 1, r 2,...
Hanoi TowerHanoi Tower
Legend: Inside a Vietnamese temple there are three rods (labeled as r1, r2, and r3), surrounded by n golden disks of different sizes. The monks of Hanoi wants to move these disks from r1 to r3 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
Input and output formatInput and output format Input: A single integer n in [1, 20]
Output: The steps to move the disks from r1 to r3; in the format of ri -> rj
3
r1 -> r3r1 -> r2r3 -> r1r1 -> r3r2 -> r1r2 -> r3r1 -> r3
RecursionRecursion Can we solve the problem by solving some smaller
problems?
To move n disks from r1 to r3
1. move n-1 disks from r1 to r2
2. move 1 disks from r1 to r3
3. move n-1 disks from r2 to r3
r1 r2 r3
ImplementationImplementation 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" << i << " -> 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;}
How many moves are there?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
= ...
= 2n-1 T(1)+ 2n-2 + ... + 1
= 2n - 1 The running time is also Θ(2n) = exponential time Very slow But it is optimal already (prove by M.I. on n)
Other recursion problemsOther recursion problems http://net.pku.edu.cn/~course/cs101/2007/book2/
pp_list.txt Look for easy problems first
POJ 1920
SummarySummary 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