算法(35)-暴力递归(3)-汉诺塔-C++

小朋友的益智玩具,就是把一些圈圈从a->移到c,小的在上面,大的在下面。问你怎么做。

下面是图解:

写成代码就是:

先上个好理解版本的代码
 

if(N==1) 为basecase

void all(int N)
{
    //开始位置:左->右
    LeftToRight(N);
}
//1.左->右 三步 1.左到中 2.左到右 3.中到右
void  LeftToRight(int N)
{
    if(N==1)
    {
       cout<<"move 1 to left"<<endl;
    }
    else//N>1
    {
        LeftToMid(N-1);
        cout<<"move N from left to right"<<endl;
        MidToRight(N-1);
    }   
}

//2 左->中  1.左-右 2.左->中  3.右->中
void  LeftToMid(int N)
{
    if(N==1)
    {
       cout<<"move 1 to left"<<endl;
    }
    else//N>1
    {
        LeftToRight(N-1);
        cout<<"move N from left to mid"<<endl;
        RighttoMid(N-1);
    }   
}
//3.右->中 1.右->左 2.右->中 3.左—>中
void RightToMid(int N)
{
    if(N==1)
    {
       cout<<"move 1 to left"<<endl;
    }
    else//N>1
    {
        LeftToMid(N-1);
        cout<<"move N from left to right"<<endl;
        MidToRight(N-1);
    }   
}
//4.右->左 1.右->中 2.右->左 3.中—>左
void RightToLeft(int N)
{
    if(N==1)
    {
       cout<<"move 1 to right"<<endl;
    }
    else//N>1
    {
        //1.左->中 左->右 中->右
        RightToMid(N-1);
        cout<<"move N from right  to left"<<endl;
        MidToLeft(N-1);
    }   
}
//5.中->右 1.中->左 2.中->右 3.左—>右
void MidToRight(int N)
{
    if(N==1)
    {
       cout<<"move 1 to left"<<endl;
    }
    else//N>1
    {
        ToMidToLeft(N-1);
        cout<<"move N from Mid to right"<<endl;
        LeftToRight(N-1);
    }   
}
//6.中->左 1.中->右 2.中->左 3.右—>左
void MidToLeft(int N)
{
    if(N==1)
    {
       cout<<"move 1 to right"<<endl;
    }
    else//N>1
    {
        MidToRight(N-1);
        cout<<"move N from mid to left"<<endl;
        RightToLeft(N-1);
    }   
    
}

上面是过程,来个优雅简洁版的。
 

void func(int rest, int down, string from, string help, string to) {
	if (rest == 1)
	{
		cout << "move " << down << " from " << from << " to " << to << endl;
	}
	else
	{
		func(rest - 1, down - 1, from, to, help);
		func(1, down, from, help, to);
		func(rest - 1, down - 1, help, from, to);
	}
}
void hanoi(int n) 
{
	if (n > 0) 
	{
		func(n, n, "left", "mid", "right");
	}
}



void hanoi_main()
{
	cout<<"***hanoi_main******"<<endl;
	int n = 3;
	hanoi(n);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值