用栈模拟汉诺塔问题
闲来无事研究了一下这个经典的递归问题。
整个过程可以用3个栈来模拟。假设我们要把1-N这N个数从栈1挪到栈3,具体步骤可以递归描述为:
- 把栈1顶部的N-1个数挪到栈2。
- 把栈1底部的N挪到栈3。
- 把栈2的N-1个数挪到栈3。
时间复杂度O(2^n)。实现如下:
#include <stack> #include <assert.h> using namespace std; class Hanoi{ public: void Move(int n, stack<int> *s1, stack<int> *s2, stack<int> *s3); private: void MoveTop(stack<int> *s1, stack<int> *s2); };
#include "Hanoi.h" void Hanoi::Move(int n, stack<int> *s1, stack<int> *s2, stack<int> *s3) { if(n == 1) { MoveTop(s1, s3); return; } Move(n-1, s1, s3, s2); MoveTop(s1, s3); Move(n-1, s2, s1, s3); } void Hanoi::MoveTop(stack<int> *s1, stack<int> *s2) { if(s1 && s2 && !s1->empty()) { int n = s1->top(); s1->pop(); if(!s2->empty()) { assert(n < s2->top()); } s2->push(n); } }
#include <iostream> #include "Hanoi.h" using namespace std; int main() { stack<int> s1, s2, s3; int n = 3; for(int i = n; i > 0; i--){ s1.push(i); }; Hanoi h; h.Move(n, &s1, &s2, &s3); while(!s3.empty()){ cout<<s3.top(); s3.pop(); } return 0; }
浙公网安备 33010602011771号