(算法)Hanoi Problem汉诺塔问题

本文详细介绍了经典的汉诺塔问题及其递归解决方案。通过具体的C++代码实现,展示了如何将N个不同大小的盘子从初始柱子移动到目标柱子,同时遵循规则:每次只能移动一个盘子且始终保持较轻的盘子位于较重盘子之上。

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

Problem:

There are three poles and N disks where each disk is heaver than the next disk. In the initial conguration, the discs are stacked upon another on the first pole where the lighter discs are above the heavier discs. We want to move all the discs to the last pole with the following conditions:

  • Only one disc can be moved from one pole to another at a time.
  • The discs have to be stacked such that all the lighter discs are on top of the heavier ones.

Recursion:

To move N discs from the first pole to the last pole, we need to move N-1 discs to the middle pole, then move the Nth disc to the last pole, and then move all N-1 discs from the middle pole back to the last pole.

Code: 

#include <iostream>

using namespace std;

void hanoi(int N,int start,int helper,int destination){
    if(N==1)
        cout<<"Move "<<start<<" to "<<destination<<endl;
    else{
        hanoi(N-1,start,destination,helper);
        hanoi(1,start,helper,destination);
        hanoi(N-1,helper,start,destination);
    }
}

int main()
{
    int N=10;
    hanoi(10,1,2,3);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值