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)
        }
        
    }
}

 

posted @ 2013-03-04 17:18  天天_byconan  阅读(256)  评论(0编辑  收藏  举报