题目:*18.18 (汉诺塔)
修改程序清单18-8,使程序可以计算将n个盘子从塔 A 移到塔 B 所需的移动次数
- 提示:使用一个静态变量,每当调用方法一次,该变量就加1。
代码示例
编程练习题18_18Hanoi.java
package chapter_18;
import java.util.Scanner;
public class 编程练习题18_18Hanoi {
private static int times = 0;//静态变量
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of disks: ");
int n = input.nextInt();
System.out.println("The moves are: ");
moveDisks(n, 'A', 'B', 'C');
System.out.println("times is: "+times);
}
public static void moveDisks(int n,char fromTower,
char toTower,char auxTower) {
times++;//方法被调用时+1
if (n == 1)
System.out.println("Move disk "+n+" from "+
fromTower + " to "+toTower);
else {
moveDisks(n-1, fromTower, auxTower, toTower);
System.out.println("Move disk "+n+" from "+
fromTower + " to "+toTower);
moveDisks(n-1, auxTower, toTower, fromTower);
}
}
}
-
输出结果
Enter number of disks: 3
The moves are:
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Move disk 3 from A to B
Move disk 1 from C to A
Move disk 2 from C to B
Move disk 1 from A to B
times is: 7