关于java:代码-汉诺塔汉诺塔问题

42次阅读

共计 1860 个字符,预计需要花费 5 分钟才能阅读完成。

问题形容

给定三根柱子 A,B,C,柱子 A 上依照大小程序放着 n 个大小不同的盘子,最上面的最大,最下面的最小,输出盘子的个数,当初要把柱子 A 上的盘子全副挪动到 C 上。

问:
起码要挪动多少次,输入每一步挪动的形式。
输出开始计数的步骤和完结技术的步骤,统计在此期间每一个步骤呈现的次数。

代码
package Ring1270.pra.java01;
import java.sql.SQLOutput;
import java.util.Scanner;
/**
 * https://www.lanqiao.cn/courses/2786/learning/?id=67029 */public class F_TowerOfHanoi {
    //Constants
 static int STEP = 0;
    static int AB = 0;
    static int AC = 0;
    static int BC = 0;
    static int BA = 0;
    static int CA = 0;
    static int CB = 0;
    //Method of count
 public static void count(String s) {if ("A-->B".equals(s)) AB++;
        if ("A-->C".equals(s)) AC++;
        if ("B-->A".equals(s)) BA++;
        if ("B-->C".equals(s)) BC++;
        if ("C-->A".equals(s)) CA++;
        if ("C-->B".equals(s)) CB++;
    }
    //Method of output
 public static void prin() {System.out.println("A-->B :" + AB);
        System.out.println("A-->C :" + AC);
        System.out.println("B-->A :" + BA);
        System.out.println("B-->C :" + BC);
        System.out.println("C-->A :" + CA);
        System.out.println("C-->B :" + CB);
    }
    //Method of tower's moving
 public static void move(int n, String from, String pass, String to, int x, int y) {if (n == 1) {System.out.println("Step" + ++STEP + ":" + "第 1 个盘子从" + from + "挪动到" + to + ",记为:" + from + "-->" + to);
            if (STEP >= x) {
                String s = from + "-->" + to;
                count(s);
            }
        } else {
            // 当有两个盘子的时候, 这里相当于把第一个挪动到 B 柱子上
 move(n - 1, from, to, pass, x, y);
            System.out.println("Step" + ++STEP + ":" + "将" + n + "个盘子从" + from + "挪动到" + to + ",记为:" + from + "-->" + to);
            if (STEP >= x) {
                String s = from + "-->" + to;
                count(s);
            }
            // 而后把第二个盘子挪动,相当于把两头挪动到 C 下面去
 move(n - 1, pass, from, to, x, y);
        }
    }
    //Method of main
 public static void main(String[] args) throws Exception {Scanner scanner = new Scanner(System.in);
        System.out.println("Input the number of work's time:");
        int n = scanner.nextInt();
        System.out.println("Input the step of start:");
        int x = scanner.nextInt();
        System.out.println("Input the step of end:");
        int y = scanner.nextInt();
        if (x <= 0 || x > Math.pow(2, n) - 1 || x >= y) {throw new Exception("The start number is error , Runing is over......");
        }
        if (y <= 0 || y > Math.pow(2, n) - 1 || y <= x) {throw new Exception("The end number is error, Runing is over......");
        }
        int p = 0;
        move(n, "A", "B", "C", x, y);
        prin();}
}
运行截图

正文完
 0