双色汉诺塔问题:
分析:设盘子原来在A柱上,目标为B、C柱。显然与单色汉诺塔问题相同为典型的递归问题。将最后的盘子移动的目标步骤为:
(1) 除最后两个盘子外,将所有的盘子移动到C;
(2) 将最后的两个盘子移动到B;
(3) 再将C上所有的盘子移动到A;
(4) 最后将B上的一个盘子移动C。
易得移动出最后两个盘子以外,可以将大小相同颜色不同的盘子看作一个来移动,因此下边提到的个数均代表大小相同颜色不同的盘子。将n个盘子(实际盘子个数位2n)从A移动到C的步骤为:
(1) 首先将n – 1个盘子从A移动到B;
(2) 将最后的盘子从A移动到C;
(3) 再将B上的盘子移动到C。
经三步便可将所有的盘子从A移动到目标C。再加上上述的将最后的盘子移动到目标的步骤便可完成全部盘子的移动过程。
C++参考代码如下,函数入口test(int disks);
class CHanoi
{
public:
CHanoi(void);
~CHanoi(void);
public:
void hanoi(int disks, char source, char temp, char target);
void hanoi2colors(int disks);
void test(int disks);
};
CHanoi::CHanoi(void)
{
}
CHanoi::~CHanoi(void)
{
}
void CHanoi::hanoi(int disks, char source, char temp, char target)
{
//这儿的1表示有两个盘子
if (1 == disks)
{
cout<<"move disk from "<<source<<" to "<<target<<endl;
cout<<"move disk from "<<source<<" to "<<target<<endl;
}
else
{
hanoi(disks - 1, source, target, temp);
hanoi(1, source, temp, target);
hanoi(disks - 1, temp, source, target);
}
}
void CHanoi::hanoi2colors(int disks)
{
char source = 'A';
char temp = 'B';
char target = 'C';
//注意i > 1,则必须处理最后一个
for (int i = disks / 2; i > 1; i--)
{
hanoi(i - 1, source, temp, target);
cout<<"move disk from "<<source<<" to "<<temp<<endl;
cout<<"move disk from "<<source<<" to "<<temp<<endl;
hanoi(i - 1, target, temp, source);
cout<<"move disk from "<<temp<<" to "<<target<<endl;
}
cout<<"move disk from "<<source<<" to "<<temp<<endl;
cout<<"move disk from "<<source<<" to "<<target<<endl;
}
void CHanoi::test(int disks)
{
hanoi2colors(disks);
}