【代码 -- 汉诺塔】汉诺塔问题

问题描述

给定三根柱子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();
    }
}
运行截图

image

你可能感兴趣的:(java)