1. 程式人生 > >遞迴方法----漢諾塔問題

遞迴方法----漢諾塔問題

遞迴思想解決 漢諾塔問題

1
package Recursive; 2 3 public class TestHanoi { 4 public static void main(String[] args) { 5 hanoi(3,'A','B','C'); 6 } 7 8 /** 9 * 10 * @param n 共有N個盤子 11 * @param from 開始的柱子 12 * @param in 中間的柱子 13 * @param to 目標柱子 14 */ 15
public static void hanoi(int n,char from,char in,char to){ 16 if(n==1){ 17 System.out.println("第一個盤子從"+from+"移到"+to); 18 19 }else{ 20 //移動上面所有的盤子到中間位置 21 hanoi(n-1,from,to,in); 22 //移動下面的盤子 23 System.out.println("第"+n+"個盤子從"+from+"移到"+to);
24 //把上面的所有盤子從中間位置移到目標位置 25 hanoi(n-1,in,from,to); 26 } 27 28 } 29 30 }