- /**
- * 汉诺塔问题
- *
- * 精确计算出到底需要移动多少次才能够将汉诺塔从柱子A搬到柱子B(柱子C作缓冲)
- * 输入:汉诺塔的层次数
- * 输出:移动次数和移动动作
- * 思路:递归
- * 使用:直接在main函数new Test(汉诺塔的层次数)
- *
- * @author Fiay
- *
- */
- public class Test {
- private static String a = "柱子A";
- private static String b = "柱子B";
- private static String c = "柱子C";
- private int level;
- private int turns;
- /*省略Getter and Setter*/
- public Test(){}
- public Test(int level){
- this.level = level;
- this.turns = getTurnsByLevel(this.level);
- System.out.println("完成!\n共需要"+turns+"步");
- }
- public int getTurnsByLevel(int level){
- System.out.println("汉诺塔层次数为:"+level+"\n开始!");
- showSolution(level,a,b,c);
- return turns-1;
- }
- public void showSolution(int level,String a,String b,String c){
- if(level>0){
- showSolution(level-1,a,c,b);
- System.out.println(turns+" - 从("+a+")移到("+b+")\t");
- showSolution(level-1,c,b,a);
- }else{
- turns++;
- }
- }
- public static void main(String args[]){
- new Test(2);
- //new Test(3);
- //new Test(4);
- }
- }
【Fiay】【Java】汉诺塔算法 递归实现
最新推荐文章于 2023-11-05 16:16:46 发布