Java學習(3):遞迴問題(舉例:漢諾塔問題)。

來源:互聯網
上載者:User

標籤:i++   string   str   move   scanner   題解   ++   reader   解析   

遞迴問題是編寫程式中常見的問題之一。此隨筆對具有明顯遞迴的漢諾塔問題進行說明。

 1 import java.util.Scanner; 2  3 /** 4  * 遞迴:漢諾塔 5  * 6  * @author xcx 7  * @time 2017年7月3日上午8:16:07 8  */ 9 public class Hanoi {10     private static int i = 0;11 12     public static void main(String[] args) {13         int n = 0;14         Scanner reader = new Scanner(System.in);15         System.out.println("請輸入盤子的數量:");16         n = reader.nextInt();17         System.out.println(n + "層漢諾塔的解法是:");18         move(n, ‘A‘, ‘B‘, ‘C‘);19         System.out.println("Total:" + i);20     }21 22     private static void move(int no, char A, char B, char C) {23         i++;24         if (no == 1) {// 如果只有一個盤子,直接將盤子從A移動到C25             System.out.println("移動盤子1從" + A + "到" + C);26         } else {// 如果盤子的個數大於1個27                 // 先將n-1個盤子從A移動到B28             move(no - 1, A, C, B);29             // 再將第n個盤子移動到C30             System.out.println("移動盤子" + no + "從" + A + "到" + C);31             // 然後再將n-1個盤子從B移動到C32             move(no - 1, B, A, C);33         }34 35     }36 37 }

漢諾塔問題解析:n表示盤子的數量

if   n = 1:直接將盤子從A移動到C

if n > 1:將(n-1)個盤子從A移動到B,然後再將(n-1)個盤子從B移動到C

Java學習(3):遞迴問題(舉例:漢諾塔問題)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.