漢諾塔問題(遞歸、用棧替代遞歸)


漢諾塔問題

古代有一個梵塔,塔內有三個座A、B、C,A座上有64個盤子
,盤子大小不等,大的在下,小的在上(如圖)。有一個和尚
想把這64個盤子從A座移到B座,但每次只能允許移動一個盤子
,並且在移動過程中,3個座上的盤子始終保持大盤在下,小盤
在上。在移動過程中可以利用B座,要求輸出移動的步驟。

 

 

漢諾塔問題遞歸解法

 

C++代碼

 1 //By LYLtim
 2 //2015.2.8
 3 
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 void hanoi(int n, char src, char mid, char dst) {
 9     if (n == 1)
10         cout << src << "->" << dst << endl;
11     else {
12         hanoi(n-1, src, dst, mid);
13         cout << src << "->" << dst << endl;
14         hanoi(n-1, mid, src, dst);
15     }
16 }
17 
18 int main()
19 {
20     int n;
21     cin >> n;
22     hanoi(n, 'A', 'B', 'C');
23 
24 }

以輸入3個盤子為例輸出

A->C
A->B
A->C
C->B
B->C
B->A
A->C

 

Java代碼

 1 //By LYLtim
 2 //2011.11.12
 3 
 4 public class hanoi {
 5 
 6     public static void main(String[] args) {
 7         movdDisk(3, 1, 3, 2);
 8     }
 9 
10     static void movdDisk(int n, int start, int end, int mid) {
11         if (n == 1)
12             System.out.println("move disk 1 from post " + start + " to post " + end );
13         else {
14             movdDisk(n - 1, start, mid, end);
15             System.out.println("move disk " + n + " from post " + start + " to post " + end);
16             movdDisk(n - 1, mid, end, start);
17         }
18     }
19 }

 

漢諾塔問題非遞歸解法

漢諾塔問題手工解法(三個盤子)

信封堆,每個信封放一個待解決的問題

后進先出,用棧模擬。

 

 1 //By LYLtim
 2 //2015.2.8
 3 
 4 #include <iostream>
 5 #include <stack>
 6 
 7 using namespace std;
 8 
 9 struct Problem
10 {
11     int n;
12     char src, mid, dst;
13     Problem(){}
14     Problem(int n, char s, char m, char d) : n(n), src(s), mid(m), dst(d) {}
15 };
16 
17 int main()
18 {
19     int n;
20     cin >> n;
21     stack<Problem> stk;
22     Problem curPrb;
23     stk.push(Problem(n, 'A', 'B', 'C'));
24     while (!stk.empty()) {
25         curPrb = stk.top();
26         stk.pop();
27         if (curPrb.n == 1)
28             cout << curPrb.src << "->" << curPrb.dst << endl;
29         else {
30             stk.push(Problem(curPrb.n-1, curPrb.mid, curPrb.src, curPrb.dst));
31             cout << curPrb.src << "->" << curPrb.dst << endl;
32             stk.push(Problem(curPrb.n-1, curPrb.src, curPrb.dst, curPrb.mid));
33         }
34     }
35 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM