老师让用java实现汉诺塔,网上搜索了一篇C的实现,与大家共享:
下面是java
import java.io.*;
public class HanNuoTa{
public static void main(String[] args) throws IOException{
System.out.println("请输入你要移的盘的总数:");
int n =(int) System.in.read();
char a = 'A', b = 'B', c = 'C';
hanio(n, a, b, c);
}
public static void hanio(int n, char a, char b, char c) {
if (n == 1) { //如果只有一个盘子则直接把盘子从a 移到b
System.out.println("move " + a + " to " + b);
}
else { //超过一个盘子的情况
hanio( (byte) (n - 1), a, c, b); //将a杆上n-1个盘子借助于b先移到c杆
System.out.println("move " + a + " to " + b); //将a杆上第n个盘子从a移到b杆
hanio( (byte) (n - 1), c, b, a); //将c杆上n-1个盘子借助a移到b杆
}
}
}
下面是C:
void he(char x,char y)
{ printf("%c---->%c/n",x,y);
}
void she(int n,char first,char second,char third)
{
if(n==1)he(first,third);
else
{she(n-1,first,third,second);
he(first,third);
she(n-1,second,first,third);
}
}
main()
{
int x;
printf("input the number of diskes:");
scanf("%d",&x);
printf("the step to moving %3d diskes:/n",x);
she(x,'A','B','C');
}