漢諾塔算法java實現
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;public class HanRuoTa {
/**
漢諾塔算法 */ public static void main(String[] args) { int n =0;
BufferedReader buf; buf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("請輸入盤數:"); try {
n = Integer.parseInt(buf.readLine()); } catch (NumberFormatException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); }
HanRuoTa hanoi = new HanRuoTa();
hanoi.move(n, 'A', 'B', 'C');
}
/**
- 采用遞歸的算法去實現
*/
public void move(int n,char a,char b,char c){
if(n == 1)
}System.out.println("盤 " + n + " 由 " + a + " 移至 " + c); else { move(n - 1, a, c, b); System.out.println("盤 " + n + " 由 " + a + " 移至 " + c); move(n - 1, b, a, c); }
}</pre>
本文由用戶 y37f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!