双色汉诺塔问题
最后更新于:2022-04-01 10:11:53
双色汉诺塔问题:圆盘最初是混合颜色的从小到大排好的,现在要求根据其颜色分开到两个柱子上分别从小到大排好。三色汉诺塔问题可与此类似,分别是排到三个柱子上。
与汉诺塔问题类似,稍作一点改动,假设柱子的编号为ABC,共有n个圆盘(n为偶数)
1.将最上面的n-1个圆盘从A移动到B上面
2.将底部那个圆盘从A移动到C
3.将B柱上的n-2个圆盘移动到A上,从而形成了第二个图那样的情景
因此,可以根据一个递归的解法来解决此问题
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-02-18_56c5c49ba376b.jpg)
~~~
//双色汉诺塔问题
#include<iostream>
using namespace std;
int removeTimes = 0;
void hanoiorignal(int nmovnum, char czsource, char cztemp, char czdes)
{
if (nmovnum == 0)
{
return;
}
else if (nmovnum == 1)
{
cout<<"move the "<<nmovnum<<" disk from "<<czsource <<" to "<<czdes<<endl;
removeTimes++;
}
else
{
hanoiorignal(nmovnum -1, czsource, czdes, cztemp);
cout<<"move the "<<nmovnum<<" disk from "<<czsource <<" to "<<czdes<<endl;
removeTimes++;
hanoiorignal(nmovnum -2, cztemp, czdes, czsource);
}
}
void hanoitwocolor(int ndisk)
{
char szsource = 'a';
char sztemp = 'b';
char szdes = 'c';
for (int i = ndisk ; i > 0; i-= 2)
{
hanoiorignal(ndisk, szsource, sztemp, szdes);
}
cout<<"总共移动次数为:"<<removeTimes<<endl;
removeTimes = 0;
}
void main()
{
int ndisknum = 0;
cout<<"输入塔上的盘碟数目,必须是2的倍数,输入0结束"<<endl;
cin>>ndisknum;
while (ndisknum)
{
hanoitwocolor(ndisknum);
cout<<"输入塔上的盘碟数目,必须是2的倍数,输入0结束"<<endl;
cin>>ndisknum;
}
system("pause");
}
~~~
输入共有6个圆盘,输出结果如下:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-02-18_56c5c49bb2e99.jpg)