汉诺(Hanoi)塔问题:古代有一个梵塔,塔内有三个座A、B、C,A座上有64个盘子,盘子大小不等,大的在下,小的在上(如图)。有一个和尚想把这64个盘子从A座移到B座,但每次只能允许移动一个盘子,并且在移动过程中,3个座上的盘子始终保持大盘在下,小盘在上。在移动过程中可以利用B座,要求打印移动的步骤。
汉诺塔问题
这个问题在盘子比较多的情况下,很难直接写出移动步骤。我们可以先分析盘子比较少的情况。假定盘子从大向小依次为:盘子1,盘子2,...,盘子64。
代码解决办法:
// hanoi2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int c=0;
void move (int n, char x, char z) {
printf ("%d.move disk %d from %c to %c\n", ++c, n, x, z);
}
void hanoi (int n, char x, char y, char z)
{
if (1==n)
{
move(1,x,z);
}
else
{
hanoi(n-1,x,z,y);
move(n,x,z);
hanoi(n-1,y,x,z);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
char ch1 = 'x';
char ch2 = 'y';
char ch3 = 'z';
printf ("请输入你要移动的汉诺塔的数量:");
scanf ("%i", &n);
hanoi (n, 'x', 'y', 'z');
system("pause");
return 0;
}
// hanoi2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int c=0;
void move (int n, char x, char z) {
printf ("%d.move disk %d from %c to %c\n", ++c, n, x, z);
}
void hanoi (int n, char x, char y, char z)
{
if (1==n)
{
move(1,x,z);
}
else
{
hanoi(n-1,x,z,y);
move(n,x,z);
hanoi(n-1,y,x,z);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
char ch1 = 'x';
char ch2 = 'y';
char ch3 = 'z';
printf ("请输入你要移动的汉诺塔的数量:");
scanf ("%i", &n);
hanoi (n, 'x', 'y', 'z');
system("pause");
return 0;
}
结果见图:


被折叠的 条评论
为什么被折叠?



