Posted on 2008-10-10 15:56
追风舞者 阅读(187)
评论(0) 编辑 收藏 所属分类:
数据结构与算法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Hanoi {
public static void main(String[] args) throws NumberFormatException,
IOException {
System.out.print("请输入盘数:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
move(n, 'A', 'B', 'C');
}
/**
* 将n个盘子借助b,从 a 移到 c
*/
public static 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);
}
}
}