Chapter 17Recursion Hanoi Tower Problem 2 Hanoi Tower
Chapter 17:Recursion (递归) Hanoi Tower Problem (汉诺塔问题) 2
Hanoi Tower (汉诺塔) Rule(规则) Ø You may move only ONE disk at a time. 每次只能移动一个金盘 Ø A larger disk may not rest on top of a smaller one at any time较大的金盘不可放在 较小的金盘上
Use recursion in Hanoi Tower Problem (用递归解决汉诺塔问题) Solution(解决方法) of recursion program: 1. 2. find the recursion formula(递归公式). confirm the ending condition(边界条件) of recursion algorithm.
1、Analysis(分析): 63(N-1) 64(N) l A杆 B杆 C杆 if A has N( N>1) disks , divide it into 2 parts: top N-1 disks, and bottom disk. ① move the top N-1 disks: from A,using. C,to B ② move the bottom disk: from A,to C ③ move the top N-1 disks: from B,using A,to C
solution (解决方法) : 1. recursion formula (递归公式) if ( n > 1 ) hanoi ( n-1, A, C, B ); printf("%c %cn", A, C); hanoi ( n-1, B, A, C ); 2. Ending condition(边界条件) if ( n == 1 ) printf(" %c %cn", A, C); 9
2、Programming(编写程序): void hanoi(int n, char A, char B, char C) { if ( n>1 ) { hanoi ( n-1, A, C, B ); printf("%d: %c -> %cn", ++i, A, C); hanoi ( n-1, B, A, C ); } else printf("%d: %c -> %cn", ++i, A, C); } 10
Hanoi demo hanoi(1, A, B, C) hanoi(2, A, C, B) A B hanoi(1, C, A, B) C B hanoi(1, B, C, A) B A A C hanoi(3, A, B, C) hanoi(2, B, A, C) B C hanoi(1, A, B, C) A A C B C A C
step(64) = 264 -1 =step(63)+1+step(63) = 263 -1 =step(62)+1+step(62) … … step(2) =step(1)+1+step(1) step(1 ) =1 step(2) =1+1+1=3
3、Complexity analysis of algorithm( 算法复杂度分析): Time complexity: O(2 n)
4、Summary(小结) ü solution (解决方法) 1. 2. recursion formula (递归公式) ending condition(边界条件) ütime complexity of algorithm (算法时间复杂 度) O(2 n)
5、 Programming exercise 作业:编程设计一个Hanoi小游戏。
- Slides: 16