漢羅塔問題 java實現

星海無邊發表於2020-11-26
import java.util.Scanner;

public class TowerOfHanoi {
	//用於記錄移動的次數
	static int m = 0;
	//展示函式
	public static void move(int disk, char M, char N) {
		System.out.println("第" + (++m) + "次操作,將" + 
							disk + "號盤從" + M + "移動到" + N);
	}
	public static void hanoi(int n, char A, char B, char C) {
		if(n == 1) {
			move(n, A, C);
		}else {
			hanoi(n - 1, A, C, B);
			move(n, A, C);
			hanoi(n - 1, B, A, C);
		}
	}
	
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		System.out.println("請您輸入hanoi的個數:");
		int a = in.nextInt();
		hanoi(a, 'A', 'B', 'C');
		System.out.println("總共使用" + m + "次");
	}
}

相關文章