漢諾塔

原文鏈接:https://github.com/CyC2018/CS-Notes/blob/master/notes/算法%20-%20其它.md

有三個柱子,分別爲 from、buffer、to。需要將 from 上的圓盤全部移動到 to 上,並且要保證小圓盤始終在大圓盤上。

這是一個經典的遞歸問題,分爲三步求解:
① 將 n-1 個圓盤從 from -> buffer
② 將 1 個圓盤從 from -> to
③ 將 n-1 個圓盤從 buffer -> to

/**
 * 
 * 如果只有一個圓盤,那麼只需要進行一次移動操作。
 * 
 * 從上面的討論可以知道,a(n) = 2 * a(n-1) + 1,顯然 an = 2^n - 1,
 * 
 * n個圓盤需要移動 2^n - 1 次。
 * 
 */

public class Hanoi {

	public static void main(String[] args) {
		
		move(3,"H1","H2","H3");

	}
	public static void move (int n ,String from, String buffer, String to) {
		if (n==1) {
			System.out.println("from " + from + " to " +to);
			return;
		}
		move(n-1,from, to, buffer);
		move(1,from,buffer,to);
		move(n-1,buffer,from,to);
	}
}

輸出

from H1 to H3
from H1 to H2
from H3 to H2
from H1 to H3
from H2 to H1 
from H2 to H3
from H1 to H3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章