按递推方法,将n-1个圆盘按要求放在C塔,第n个圆盘放在B塔,现在A塔空。n号圆盘是最大的圆盘,按问题要求我们终于把n号最大的圆盘放在了B塔,这下借助已空的A塔联合BC塔推回来,就可以把n个圆盘按要求放在B塔。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hanoi {
public static void main(String args[]) throws Exception {
int n;
BufferedReader buf =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入盘数:");
n = Integer.parseInt(buf.readLine());
Hanoi hanoi = new Hanoi();
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);
}
}
} |
|