汉诺塔(Hanoi)问题

第一步:将n-1个盘子从A柱移动至B柱(借助C柱为过渡柱)

第二步:将A柱底下最大的盘子移动至C柱

第三步:将B柱的n-1个盘子移至C柱(借助A柱为过渡柱)


include <iostream>

#include <stdio.h>
using namespace std;

static int step = 0;
void move ( char sour, char dest )
{
    printf ( "move from %c to %c \n", sour, dest );
}

void hanoi ( int n, char sour, char temp, char dest )
{
    if ( n == 1 )
    {
        move ( sour, dest );
        ++step;
    }
    else
    {
        hanoi ( n-1, sour, dest, temp );
        move ( sour,dest );
        ++step;
        hanoi ( n-1, temp, sour, dest );

    }

int main ( int argc, char **argv )
{
    int n = 4;
    hanoi ( n, 'A', 'B', 'C' );
    printf ( "Total steps is %d\n", step );
    return 0;
}

}

或者:

  1. #include<cstdio>  
  2. int i;    //记录步数  
  3. //i表示进行到的步数,将编号为n的盘子由from柱移动到to柱(目标柱)  
  4. void move(int n,char from,char to){  
  5.     printf("第%d步:将%d号盘子%c---->%c\n",i++,n,from,to);  
  6. }  
  7.   
  8. //汉诺塔递归函数  
  9. //n表示要将多少个"圆盘"从起始柱子移动至目标柱子  
  10. //start_pos表示起始柱子,tran_pos表示过渡柱子,end_pos表示目标柱子  
  11. void Hanio(int n,char start_pos,char tran_pos,char end_pos){  
  12.     if(n==1){    //很明显,当n==1的时候,我们只需要直接将圆盘从起始柱子移至目标柱子即可.  
  13.         move(n,start_pos,end_pos);  
  14.     }  
  15.     else{  
  16.         Hanio(n-1,start_pos,end_pos,tran_pos);   //递归处理,一开始的时候,先将n-1个盘子移至过渡柱上  
  17.         move(n,start_pos,end_pos);                //然后再将底下的大盘子直接移至目标柱子即可  
  18.         Hanio(n-1,tran_pos,start_pos,end_pos);    //然后重复以上步骤,递归处理放在过渡柱上的n-1个盘子  
  19.                                                   //此时借助原来的起始柱作为过渡柱(因为起始柱已经空了)  
  20.     }  
  21. }  
  22. int main(){  
  23.     int n;  
  24.     while(scanf("%d",&n)==1&&n){  
  25.         i = 1;   //全局变量赋初始值  
  26.         Hanio(n,'1','2','3');  
  27.         printf("最后总的步数为%d\n",i-1);  
  28.     }  
  29.     return 0; 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值