• Java数据结构和算法——汉诺塔问题


    package com.tiantian.algorithms;
    /**
     *    _|_1              |                |
     *   __|__2             |                |
     *  ___|___3            |                |            (1).把A上的4个木块移动到C上。
     * ____|____4           |                |
     *     A                B                C
     * 
     *     |                |                |
     *     |               _|_1              |
     *     |              __|__2             |            要完成(1)的效果,必须要把1、2、3木块移动到B,这样才能把4移动到C
     * ____|____4        ___|___3            |            如:代码中的“调用(XX)”
     *     A                B                C
     *     
     *     |                |                |
     *     |               _|_1              |
     *     |              __|__2             |            此时,题目就变成了把B上的3个木块移动到C上,回到了题目(1)
     *     |             ___|___3        ____|____4        如:代码中的“调用(YY)”
     *     A                B                C
     *     
     *     然后循环这个过程
     * 
     * @author wangjie
     * @version 创建时间:2013-3-4 下午4:09:53
     */
    public class HanoiTowerTest {
        public static void main(String[] args) {
            doTowers(4, 'A', 'B', 'C');
        }
        
        public static void doTowers(int topN, char from, char inter, char to){
            if(topN == 1){
                System.out.println("最后把木块1从" + from + "移动到" + to);
            }else{
                doTowers(topN - 1, from, to, inter); // 调用(XX)
                System.out.println("把木块" + topN + "从" + from + "移动到" + to);
                doTowers(topN - 1, inter, from ,to); // 调用(YY)
            }
            
        }
    }
  • 相关阅读:
    P4665 [BalticOI 2015]Network 题解
    NOIp2020游记
    独立集(bubble) 题解
    密码(substring) 题解
    8.20被题虐
    开通博客了!
    CSP-S2021 记
    「CSP-S 2020」函数调用(拓扑排序+DP)
    OI生涯回忆录
    [UOJ79]一般图最大匹配(带花树)
  • 原文地址:https://www.cnblogs.com/tiantianbyconan/p/2943102.html
Copyright © 2020-2023  润新知