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);
}
}
}
汉诺塔(hanoi)
最新推荐文章于 2024-09-08 11:09:43 发布