zoukankan      html  css  js  c++  java
  • 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)
            }
            
        }
    }
  • 相关阅读:
    DFS-B
    DFS/BFS-A
    DFS-回溯与剪枝-C
    BFS-八数码问题与状态图搜索
    PTA-1003 我要通过!
    二分-G
    二分-F
    二分-E
    二分-D
    二分-C
  • 原文地址:https://www.cnblogs.com/tiantianbyconan/p/2943102.html
Copyright © 2011-2022 走看看