zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    不用π求坐标夹角大小
    使用LVS实现负载均衡原理及安装配置详解
    从dfs向动态规划过渡
    关于dfs
    [LeetCode] Add Two Numbers
    [LeetCode] Gray Code
    [LeetCode] Single Number
    第四章 深入JSP技术
    蚂蚁破2万亿!身价暴涨2077亿的彭蕾:无论马云的决定是什么,我都让它成为最正确的决定...
    异常场景测试
  • 原文地址:https://www.cnblogs.com/kyxyes/p/3961000.html
Copyright © 2011-2022 走看看