题目 2056: 汉诺塔
https://www.dotcpp.com/oj/problem2056.html
做题情况
参考代码:
//package Dotcpp;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// printHanoTower(5,"A","B","C");
PrintHanio(n,"1","2","3");
//n为汉诺塔高度 ,
//A定为起始位置 B定为辅助helper C定为目的地
}
//---------------------------------------------------------------------------------
private static void PrintHanio(int n, String From, String helper, String Destination ) {
/*
牢记以下几点:
1.一次汉诺塔包含两个步骤
2.递归本身就很适用于抽象概念,不要去深究为什么它能识别的过来,原因是因为递归本身就是高负载压栈下的计算
*/
if (n==1){
System.out.println("Move "+n+" from "+From+" to "+Destination);
return;
}
PrintHanio(n-1,From,Destination,helper);
//显示对第n个数的移动
System.out.println("Move "+n+" from "+From+" to "+Destination);
PrintHanio(n-1,helper,From,Destination);
}
//---------------------------------------------------------------------------------
}
递归简记:
Hanio(n,A,B,C)
调用method(N,from,help,to)
内部方法:
n==1:
sout(from,to)
return
else{
调用method(n-1,from,to,help)
sout(from,to)
调用method(n-1,help,from,to)
}