课后作业2:递归编程解决汉诺塔问题

【程序设计思想】

          将A座上盘子移到C座上,实现的操作:1,将A座上除最下面其余盘子移到B座上2,将A座上一个盘子移到C座上3,将B座上盘子移到C座上。

          分别用两个函数实现两类操作,用hanio函数实现第一类操作,用move函数实现第2类操作,函数调用hanio(n,one,two,three)表示将n个盘子从“one”座移到“three”座的过程。函数调用move(x,y)表示将一个盘子从x座移到y座的过程。

【程序流程图】

【源代码】

//那颖 信1605-2班 20163448
import java.util.Scanner;
public class Hanoi
{
public static void main(String[] args)
{
System.out.println("please input m:");
Scanner input=new Scanner(System.in);
int m=input.nextInt();
hanio(m,'A','B','C');

}

public static void move(char x,char y)
{
System.out.println(x+"->"+y);
}

public static void hanio(int n,char one,char two,char three)
{
if(n==1)
move(one,three);
else
{
hanio(n-1,one,three,two);
move(one,three);
hanio(n-1,two,one,three);
}

}
}

【运行结果截图】

原文地址:https://www.cnblogs.com/-2016/p/7663491.html