用栈模拟汉诺塔问题

闲来无事研究了一下这个经典的递归问题。

整个过程可以用3个栈来模拟。假设我们要把1-N这N个数从栈1挪到栈3,具体步骤可以递归描述为:

  1. 把栈1顶部的N-1个数挪到栈2。
  2. 把栈1底部的N挪到栈3。
  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);
};
Hanoi.h

 

#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;
}
main.cpp

 

posted on 2015-12-28 02:47  谢绝围观  阅读(190)  评论(0)    收藏  举报

导航