java编程(递归)

来源:百度知道 编辑:UC知道 时间:2024/07/05 06:14:00
5. Write a Java program to solve the Hanoi tower problem with recursion. Your class should named HanoiTower.java. The class should contain a static method with signature as follows:
public void solveHanoiTower( int numOfDisk,
char fromPole, char withPole, char toPole);

The method should print out messages like follows if there are 2 disks to move.)
Move disk 1 from pole A to pole B;
Move disk 2 from pole A to pole C;
Move disk 1 from pole B to pole C;
用程序编译出来!
答好追加分!!

public void solveHanoiTower(int numOfDisk, char fromPole, char withPole, char toPole) {
if (numOfDisk == 1) {
System.out.println("Move disk 1 from pole " + fromPole + " to pole " + toPole);
return;
}

solveHanoiTower(numOfDisk - 1, fromPole, toPole, withPole);
System.out.println("Move disk " + numOfDisk + " from pole " + fromPole + " to pole " + toPole);
solveHanoiTower(numOfDisk - 1, withPole, fromPole, toPole);
}

/* This is a first-year question. Just give a try. */