输入一个数n,表示塔层数
按样例格式输出最优移动过程和最优移动总步数
2
Move 1 from left to mid Move 1 from mid to right Move 2 from left to mid Move 1 from right to mid Move 1 from mid to left Move 2 from mid to right Move 1 from left to mid Move 1 from mid to right It will move 8 steps.
当塔数为两层时,最上层的塔记为1,最下层的塔记为2
import java.util.*; public class Main { static int steps = 0; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); HanNuo(n, "left", "mid", "right"); System.out.println("It will move "+steps+" steps."); } public static void HanNuo(int n,String a,String b,String c) { if(n==1) { System.out.println("Move "+n+" from "+a+" to "+b); System.out.println("Move "+n+" from "+b+" to "+c); }else { HanNuo(n-1,a,b,c); System.out.println("Move "+n+" from "+a+" to "+b); HanNuo(n-1,c,b,a); System.out.println("Move "+n+" from "+b+" to "+c); HanNuo(n-1,a,b,c); } steps+=2; } }