java資料結構和演算法學習之漢諾塔樣本_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

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

    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.