lintcode:227.用栈模拟汉诺塔问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode:227.用栈模拟汉诺塔问题相关的知识,希望对你有一定的参考价值。
在经典的汉诺塔问题中,有 3 个塔和 N 个可用来堆砌成塔的不同大小的盘子。要求盘子必须按照从小到大的顺序从上往下堆 (如,任意一个盘子,其必须堆在比它大的盘子上面)。同时,你必须满足以下限制条件:
(1) 每次只能移动一个盘子。
(2) 每个盘子从堆的顶部被移动后,只能置放于下一个堆中。
(3) 每个盘子只能放在比它大的盘子上面。
请写一段程序,实现将第一个堆的盘子移动到最后一个堆中。
具体思路在本笔记后面有记录!
以下为本人C++版详细过程!包括测试过程
1 class Tower { 2 public: 3 // create three towers (i from 0 to 2) 4 Tower(int i) { 5 } 6 // Add a disk into this tower 7 void add(int d) { 8 if (!disks.empty() && disks.top() <= d) { 9 printf("Error placing disk %d\\n", d); 10 std::cout << "不符合Error disk.top:"<< disks.top() << std::endl; 11 } else { 12 //cout << "成功加入:disks.push: " << d << endl; 13 disks.push(d); 14 } 15 } 16 17 // @param t a tower 18 // Move the top disk of this tower to the top of t. 19 void moveTopTo(Tower &t) { 20 // Write your code here 21 22 //std::cout <<"待加入的distks.top:"<< disks.top() << std::endl; 23 t.add(disks.top()); 24 disks.pop(); // forget to drop the top member! // 核心丢失句!说明对stack构造器不够熟悉! 25 } 26 27 // @param n an integer 28 // @param destination a tower 29 // @param buffer a tower 30 // Move n Disks from this tower to destination by buffer tower 31 void moveDisks(int n, Tower &destination, Tower &buffer) { 32 // Write your code here 33 if (n > 0) { 34 moveDisks(n-1,buffer,destination); 35 moveTopTo(destination); 36 buffer.moveDisks(n - 1, destination, *this); 37 } 38 } 39 40 stack<int> getDisks() { 41 return disks; 42 } 43 44 private: 45 stack<int> disks; 46 }; 47 /** 48 * Your Tower object will be instantiated and called as such: 49 * vector<Tower> towers; 50 * for (int i = 0; i < 3; i++) towers.push_back(Tower(i)); 51 * for (int i = n - 1; i >= 0; i--) towers[0].add(i); 52 * towers[0].moveDisks(n, towers[2], towers[1]); 53 * print towers[0], towers[1], towers[2] 54 */
C++完整版参考:
1 #include <iostream> 2 #include <stack> 3 4 using namespace std; 5 6 struct Problem 7 { 8 int n; 9 char src, mid, dst; 10 Problem(){} 11 Problem(int n, char s, char m, char d) : n(n), src(s), mid(m), dst(d) {} 12 }; 13 14 int main() 15 { 16 int n; 17 cin >> n; 18 stack<Problem> stk; 19 Problem curPrb; 20 stk.push(Problem(n, ‘A‘, ‘B‘, ‘C‘)); 21 while (!stk.empty()) { 22 curPrb = stk.top(); 23 stk.pop(); 24 if (curPrb.n == 1) 25 cout << curPrb.src << "->" << curPrb.dst << endl; 26 else { 27 stk.push(Problem(curPrb.n-1, curPrb.mid, curPrb.src, curPrb.dst)); 28 cout << curPrb.src << "->" << curPrb.dst << endl; 29 stk.push(Problem(curPrb.n-1, curPrb.src, curPrb.dst, curPrb.mid)); 30 } 31 } 32 }
以上是关于lintcode:227.用栈模拟汉诺塔问题的主要内容,如果未能解决你的问题,请参考以下文章
Java编程用栈来求解汉诺塔问题的代码实例(非递归)_java - JAVA