写了一个利用递归实现的很经典的问题 —— 汉诺塔,有兴趣的可以看看,提点意见或者建议。代码如下:
- package sample.test1;
- import java.util.Scanner;
- /**
- * 递归算法实现汉诺塔
- */
- public class Hanoi {
- private static final String FROM = "diskA";
- private static final String MID = "diskB";
- private static final String TO = "diskC";
- public static void main(String[] args) {
- while (true) {
- System.out.print("请输入需要移动的数目:");
- Scanner inputScanner = new Scanner(System.in);
- String input = inputScanner.nextLine();
- try {
- // 判断输入是否有效
- if (checkIfInteger(input)) {
- int num = Integer.parseInt(input);
- // 进行移动
- HanoiMove(num, FROM, MID, TO);
- System.out.println("移动完成");
- inputScanner.close();
- return;
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
- }
- /**
- * 递归实现汉诺塔
- *
- * @param num
- * @param from
- * @param mid
- * @param to
- */
- public static void HanoiMove(int num, String from, String mid, String to) {
- // 递归出口
- if(num == 1){
- System.out.println("将disk1从" + from + "移到" + to);
- } else {
- // 先循环处理num-1个盘子,从初始A托盘移到中间B托盘
- HanoiMove(num - 1, from, to, mid);
- // 处理最后一个盘子,从初始A托盘移到目标C托盘
- System.out.println("将disk" + num + "从" + from + "移到" + to);
- // 将已经处理过的num-1个盘子再从中间B托盘移到目标C托盘
- HanoiMove(num - 1, mid, from, to);
- }
- }
- /**
- * 判断输入的是否为数字
- *
- * @param input
- * @return
- * @throws Exception
- */
- public static boolean checkIfInteger(String input) throws Exception {
- if (input != null && input.matches("^[0-9]+$")) {
- return true;
- } else {
- throw new Exception("请输入一个数字");
- }
- }
- }
复制代码 粘过来没格式了= =
|
|