描述
经典的汉诺塔问题……别 说还不知道。
现在有3个针A,B,C;
初始状态:1,2,3,4…N个盘子在A针上串着,编号大小代表盘子大小,大 盘子一定在小盘子下面放着。
目标状态:这N个盘子从底向上的顺序是从大盘子到小盘子,也就是从N到1号盘子放在C柱子上。
规则:每步可以移动A,B,C三个柱子中某个柱子的最上面的一个盘子到另外个柱子的最上面,要保证大盘子一定在小盘子下面。
现在的问题是:请打印出 移动过程,要求使用最少步数。
输入
输入{dy}行包含一个整数T,表示有T组数据;
以下T行每行包含一个整数N,表示有N个盘子。
输出
对于每组数据输出格式如 下:
{dy}行包含一个整数M,表示最少需要M步;
一下M行每行格式如
A->B (这里表示把A柱子上的最上面盘子移动到B柱 子上)形式;
样例输入
样例输出
7
A->C
A->B
C->B
A->C
B->A
B->C
A->C
解题思路:
在学C语言的时候会遇到这个经典问题,书上也会有详细代码。这里我是抄书的,几个函数就能搞定。
#include <stdio.h>
int i;
void move(char x,char y)
{printf("%c->%c\n",x,y);}
void hanoi (int n,char one ,char two,char three)
{
if(n==1) move (one ,three);
else
{
hanoi (n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
void move1(char x,char y)
{i++;
}
void hanoi1 (int n,char one ,char two,char three)
{
if(n==1) move1 (one ,three);
else
{
hanoi1 (n-1,one,three,two);
move1(one,three);
hanoi1(n-1,two,one,three);
}
}
main()
{int m;
int number,te;
scanf("%d",&number);
for(te=1;te<=number;te++)
{
i=0;
scanf("%d",&m);
hanoi1(m,'A','B','C');
printf("%d\n",i);
hanoi(m,'A','B','C');
}
}