汉诺塔 Java 简单实现

public class HanoiTower {

    private static final Stack<Integer> source = new Stack<>(){
        @Override
        public synchronized int hashCode() {
            return 101;
        }
    };
    private static final Stack<Integer> buffer = new Stack<>(){
        @Override
        public synchronized int hashCode() {
            return 102;
        }
    };
    private static final Stack<Integer> target = new Stack<>(){
        @Override
        public synchronized int hashCode() {
            return 103;
        }
    };

    private static int totalCount = 0;

    /**
     * 移动思路: 将圆盘分为底层圆盘和上册 n-1 个圆盘两个部分递归移动
     */
    public static void move(int count, Stack<Integer> source, Stack<Integer> buffer, Stack<Integer> target){
        if (count == 1) {
            indeedMove(source, target);
            return;
        }
        // 将上层 n - 1 个圆盘以 target 为 buffer 进行移动
        move(count - 1, source, target, buffer);
        // 将底层从 source 移动到 target
        move(1, source, buffer, target);
        // 将缓存栈的 n-1 个圆盘移动到 target
        move(count - 1, buffer, source, target);
    }

    /**
     * 栈内的数据移动
     * @param source 源站
     * @param target 目标栈
     */
    public static void indeedMove(Stack<Integer> source, Stack<Integer> target){
        final Integer pop = source.pop();
        target.push(pop);
        totalCount++;
        System.out.println("数据 [" + pop + "] 从栈 [" + source.hashCode() + "] 移动到栈 [" + target.hashCode() + "]");
    }

    private static void printStack(Stack<Integer> stack){
        System.out.println("栈[" + stack.hashCode() + "] :: " + stack.toString());
    }

    public static void printAllStack(){
        printStack(source);
        printStack(buffer);
        printStack(target);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入初始的数据个数: ");
        int count = scanner.nextInt();
        for (int i = count; i > 0; i--) {
            source.push(i);
        }
        printAllStack();
        move(count, source, buffer, target);
        System.out.println("总共执行了 " + totalCount + " 次移动");
        printAllStack();
    }
}

使用三个整数栈模拟汉诺塔移动问题

测试
请输入初始的数据个数: 6
栈[101] :: [6, 5, 4, 3, 2, 1]
栈[102] :: []
栈[103] :: []
数据 [1] 从栈 [101] 移动到栈 [102]
数据 [2] 从栈 [101] 移动到栈 [103]
数据 [1] 从栈 [102] 移动到栈 [103]
......
总共执行了 63 次移动
栈[101] :: []
栈[102] :: []
栈[103] :: [6, 5, 4, 3, 2, 1]
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值