汉诺塔算法:古代有一个梵塔,塔内有ABC三个座,开始时,A座上有16个盘子,盘子的大小不一,大的在下,小的在上。有一个老和尚想把A座上的盘子移动到C座上,每次只允许移动一个盘子,且移动过程中始终是大的在下,小的在上,如何实现?
核心思想:
1.递归
2.只要盘子数不是1,那么总是先把A上的盘子借助C移动到B上,然后再借助A将B上的移动到C上
public class Hanoi { private static void move(char x,char y){ System.out.printf("%c-->%c",x,y); System.out.println(); } private static void hanoi(int n,char one,char two,char three){ //如果只有一个盘子,直接移动到C座上即可 if (n==1){ move(one,three); } else { //将A座上的盘子借助C移动到B座上 hanoi(n-1,one,three,two); move(one,three);//移动 hanoi(n-1,two,one,three);//将B座上的盘子借助A座移动到C座上 } } public static void main(String[] args){ int m; System.out.println("请输入盘子的个数:"); Scanner scanner=new Scanner(System.in); m=scanner.nextInt(); System.out.println("移动"+m+"个盘子的步骤如下:"); hanoi(m,'A','B','C'); } }
运算结果: