首页 > 代码库 > 汉诺塔问题C++实现

汉诺塔问题C++实现

#include <iostream.h>

 

 

int gbsx( char & L, char & R  )    //改变顺序的函数

{  char T ;

       T= L ;

       L= R ;

       R= T ;

       return0 ;

}

 

void move( int n , char a , char b , char c)      //汉诺塔核心函数

{  

       if( n == 1 )

       {  

              cout<< "移动"<< a  << "" << c << endl ;

       }

       else

       {   gbsx( b , c );                    //改变后面两个的顺序

     move( n - 1 , a , b , c );                //用递归实现其步骤

      

           gbsx( b , c );                    //把后面那两个的顺序换回来

       move( 1 , a , b , c);

      

       gbsx(a , b );                       //改变前面两个的顺序

       move(n - 1 , a , b , c );               //用递归实现其步骤

       }

      

}

 

int sum( int n )                         //用来计算步骤数的函数

{

       ints = 1 ;

       for(int i = 1 ; i <= n ; i++ )

   {   

              s= s*2 ;

       }

       returns-1 ;

}

 

void main()                            //主函数

{  int n = 1 ;

       cout<< "请输入您所放的盘子数目"<< endl ;          

       cin>> n ;                                //通过输入的值赋给n来实现

       cout<<  "共有" << sum ( n ) <<","<< "步骤为"<< endl ;

   move( n , ‘A‘ , ‘B‘ , ‘C‘ );                    //调用函数

}

 

汉诺塔问题C++实现