汉诺塔

本文介绍了一种解决汉诺塔问题的方法,包括递归和非递归两种实现方式。通过具体的C++代码示例展示了如何移动不同数量的盘子,并详细解释了每一步的操作逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class term{
public:
    term(int f, int tmp, int t, int n, int flag) :from(f),tmp(tmp) , to(t), n(n),flag(flag){}
    int from;
    int to;
    int tmp;
    int n;//表示从1...n的汉诺塔
    int flag;//表示要输出的
};

void move(int from, int to, int n) {
    cout<<"move "<<n<<" from "<<from<<" to "<<to<<endl;
}

void hanoi(int from, int tmp, int to, int n) {//
    if (n >0) {
        hanoi(from,to, tmp , n-1);
        move(from,to,n);
        hanoi(tmp,from, to, n-1);
        
    }
}

void nonRecurHanoi(int from, int tmp, int to, int n) {
    stack<term> st;


    st.push(term(from, tmp, to,n,n==1?1:0));
    while(!st.empty()) {
        term t = st.top();
        st.pop();

        if (t.flag) {
            move(t.from,t.to,t.n);
        }
        else {
            int flag = 0;
            if (t.n - 1 ==1)
                flag = 1;
            st.push(term(t.tmp,t.from,t.to,t.n - 1, flag));//这里的顺序和递归调用的顺序正好相反
            st.push(term(t.from,t.tmp,t.to,t.n,1));
            st.push(term(t.from, t.to, t.tmp, t.n -1 , flag));
        }
    }
}

int main() 
{ 
    hanoi(0,1,2,4);
    cout<<endl;
    nonRecurHanoi(0,1,2,4);
    return 0; 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值