题目描述
汉诺塔问题比较经典,这里修改一下游戏规则:现在限制不能从最左侧的塔直接移动到最右侧,也不能从最右侧直接移动到最左侧,
而是必须经过中间。求当塔有n层的时候,打印最优移动过程和最优移动总步数。
输入描述:
输入一个数n,表示塔层数
输出描述:
按样例格式输出最优移动过程和最优移动总步数
示例1
输入
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.Scanner;publicclassMain{publicstaticvoidmain(String[] args){
Scanner sc =newScanner(System.in);int n = Integer.valueOf(sc.nextLine());//input checkif(n<1)return;int res =hanoi(n,"left","right");
System.out.println("It will move "+ res +" steps.");}publicstaticinthanoi(int n, String from, String to){//base caseif(n==1){if(from.equals("mid")|| to.equals("mid")){
System.out.println("Move "+ n +" from "+ from +" to "+ to);return1;}else{
System.out.println("Move "+ n +" from "+ from +" to "+"mid");
System.out.println("Move "+ n +" from "+"mid"+" to "+ to);return2;}}//if(from.equals("mid")|| to.equals("mid")){
String oth = from.equals("mid")?(to.equals("left")?"right":"left"):(from.equals("left")?"right":"left");int part1 =hanoi(n-1, from, oth);
System.out.println("Move "+ n +" from "+ from +" to "+ to);int part3 =hanoi(n-1, oth, to);return part1 +1+ part3;}else{int part1 =hanoi(n-1, from, to);
System.out.println("Move "+ n +" from "+ from +" to "+"mid");int part3 =hanoi(n-1, to, from);
System.out.println("Move "+ n +" from "+"mid"+" to "+ to);int part5 =hanoi(n-1, from, to);return part1 + part3 + part5 +2;}}}