一个简单的汉诺塔游戏代码,很简单,不过挺有意思

#include "stdafx.h"
#include<iostream>

using namespace std;

class hanio  //定义一个类
{
public :
    ~hanio(){}  //析构函数
    void  han(int n,char a,char b,char c)
    {
        if(n==1)
        {
            move(a,c);  //汉诺塔主要利用了递归的套路,不过其中的规律得提前找到,这是当n=1时考虑的情况
        }
        else   //这就是当n>1考虑的情况
        {
            han(n-1,a,c,b);  //这个执行2^(n-1)-1次,如果n取3,那就3次,
            move(a,c);  //执行一次
            han(n-1,b,a,c);  //这个也同样执行2^(n-1)-1次,如果n取3,那就3次,所以总共执行刚好2^3-1=7次
        }

    }
private:
    void move(char a,char b)//定义私有化成员函数,只允许本类成员调用
    {
        cout<<"由"<<a<<"-->"<<b<<endl;
    }

};

void main()
{
    hanio h;//创建一个具体的对象
    cout<<"汉诺塔的转移次序:"<<endl;
    h.han(3,'a','b','c');//转移2^n-1,而这里的n=3,所以共2^3-1次

}

 


汉诺塔C++代码

相关文章:

  • 2021-05-31
  • 2021-07-09
  • 2021-07-15
  • 2021-11-05
  • 2022-12-23
  • 2021-10-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案