資源簡介
【實例簡介】java算法漢諾塔(hanoi)
【核心代碼】
【核心代碼】
public class Hanoi { /** * Hanoi塔問題 */ public static void main(String[] args) { try { Scanner s = new Scanner(System.in); System.out.print("請輸入圓盤個數 n="); int n = s.nextInt(); System.out.println("移動過程:"); hanoi(n, 'a', 'b', 'c'); // String n; // InputStreamReader isr=new InputStreamReader(System.in); // BufferedReader br=new BufferedReader(isr); // System.out.print("請輸入圓盤個數 n="); // n=br.readLine(); // hanoi(Integer.parseInt(n),'a','b','c'); } catch (Exception e) { e.printStackTrace(); } } public static void hanoi(int n, char a, char b, char c) { if (n == 1) { // 只有一個圓盤時 System.out.println("Move Disc No:" n " from pile " a " to " b); } else { // 先把a上的n-1個圓盤借助b移到c上 hanoi(n - 1, a, c, b); // 再把a上最大的圓盤移到b上 System.out.println("Move Disc No:" n " from pile " a " to " b); // 然后把c上的n-1個圓盤借助a移到b上 hanoi(n - 1, c, b, a); } } }
代碼片段和文件信息
import?java.util.Scanner;
public?class?Hanoi?{
/**
?*?Hanoi塔問題
?*/
public?static?void?main(String[]?args)?{
try?{
Scanner?s?=?new?Scanner(System.in);
System.out.print(“請輸入圓盤個數?n=“);
int?n?=?s.nextInt();
System.out.println(“移動過程:“);
hanoi(n?‘a‘?‘b‘?‘c‘);
//?String?n;
//?InputStreamReader?isr=new?InputStreamReader(System.in);
//?BufferedReader?br=new?BufferedReader(isr);
//?System.out.print(“請輸入圓盤個數?n=“);
//?n=br.readLine();
//?hanoi(Integer.parseInt(n)‘a‘‘b‘‘c‘);
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
public?static?void?hanoi(int?n?char?a?char?b?char?c)?{
if?(n?==?1)?{
//?只有一個圓盤時
System.out.println(“Move?Disc?No:“?+?n?+?“?from?pile?“?+?a?+?“?to?“
+?b);
}?else?{
//?先把a上的n-1個圓盤
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????目錄???????????0??2013-10-22?21:12??hanoi\
?????文件?????????301??2013-10-22?21:12??hanoi\.classpath
?????文件?????????381??2013-10-22?21:12??hanoi\.project
?????目錄???????????0??2013-10-22?21:12??hanoi\.settings\
?????文件?????????598??2013-10-22?21:12??hanoi\.settings\org.eclipse.jdt.core.prefs
?????目錄???????????0??2013-10-22?21:12??hanoi\bin\
?????文件????????1504??2013-10-22?21:12??hanoi\bin\Hanoi.class
?????目錄???????????0??2013-10-22?21:12??hanoi\src\
?????文件????????1137??2013-10-22?21:12??hanoi\src\Hanoi.java
評論
共有 條評論