Hanoi

这种A-》C是不用递归的,移动的是当前柱子中最下面一个盘子

同理,A->C上面的一组是递归,但是递归里面包含类似于A->C这样的,即Move disk 2 from Ato B

     

这种A-》C是不用递归的,移动的是当前柱子中最下面一个盘子

同理,A->C上面的一组是递归,但是递归里面包含类似于A->C这样的,即Move disk 3 from A to B

Move disk 3 from A to B上面又是一组递归 ,类似的即Move disk 2 from A to C

#include <stack>
struct op{
    int begin, end;
    char start,buff,dest;
    op(){}  //op(){}
    op(int pbegin,int pend, int pstart,int pbuff,int pdest):begin(pbegin), end(pend), start(pstart), buff(pbuff),dest(pdest){} //for struct init ,存放在stack里面
};
void haoni(int n, char start, char buff, char dest)
{
    stack<op> st; //生成存放op的stack
    op temp;
    st.push(op(1,n,start,buff,dest));
    while (!st.empty())
    {
        temp=st.top();//获取stack中当前的op,开始就是main中输入的(A,B,C),输入进temp,然后循环获取top输入进temp
        st.pop();//指针向下移动,又从-1开始 ,前面的相当于不在了,只是输给temp
        
    if(temp.begin!=temp.end)
    {
        //初始化这个op再压入stack
        st.push(op(temp.begin,temp.end-1,temp.buff,temp.start,temp.dest));//递归完成从B柱->到c柱 (3步骤)
        st.push(op(temp.end,temp.end,temp.start,temp.buff,temp.dest));//Move disk 3 from A to C(2步骤)
        st.push(op(temp.begin,temp.end-1,temp.start,temp.dest,temp.buff));//递归完成从A柱->到B柱 (1步骤)
    }else
    {
        cout<<"Move disk "<<temp.begin<<" from "<<temp.start<<" to "<<temp.dest<<endl;
    }
    }
}
int main()
{
    int n=3;
    haoni(n,'A','B','C');
    return 0;
}
原文地址:https://www.cnblogs.com/kyxyes/p/3961000.html