将递归函数程序中的直接打印语句也设计成调用递归函数towers()。直接打印语句如下: System.out.println("圆盘 " + n + " 从柱子 " + A + " 移动到柱子 " + C); =,-怎么解啊下面是普通的汉诺塔代码
public class Exam6_3{
public static void towers(int n, char A, char C, char B){
if(n == 1){
System.out.println("圆盘 1 从柱子 " + A + " 移动到柱子 " + C);
return;
}
towers(n-1, A, B, C); // 先让道:n-1个圆盘移动到柱子B
System.out.println("圆盘 " + n + " 从柱子 " + A + " 移动到柱子 " + C);
towers(n-1, B, C, A); // 再自己:n-1个圆盘移动到柱子C
} public static void main(String[] args){
System.out.println("柱子: A B C");
System.out.println("作者 http://www.niuwanet.com/");
System.out.println("n = 3");
towers(3, 'A', 'C', 'B');
}
}
public class Exam6_3{
public static void towers(int n, char A, char C, char B){
if(n == 1){
System.out.println("圆盘 1 从柱子 " + A + " 移动到柱子 " + C);
return;
}
towers(n-1, A, B, C); // 先让道:n-1个圆盘移动到柱子B
System.out.println("圆盘 " + n + " 从柱子 " + A + " 移动到柱子 " + C);
towers(n-1, B, C, A); // 再自己:n-1个圆盘移动到柱子C
} public static void main(String[] args){
System.out.println("柱子: A B C");
System.out.println("作者 http://www.niuwanet.com/");
System.out.println("n = 3");
towers(3, 'A', 'C', 'B');
}
}
public class Exam6_3{
public static void towers(int n, char A, char C, char B) {
if (n == 1) {
towers("圆盘 1 从柱子 " + A + " 移动到柱子 " + C);
return;
}
towers(n - 1, A, B, C); // 先让道:n-1个圆盘移动到柱子B
towers("圆盘 " + n + " 从柱子 " + A + " 移动到柱子 " + C);
towers(n - 1, B, C, A); // 再自己:n-1个圆盘移动到柱子C
}
public static void towers(String msg)
{
System.out.println(msg);
} public static void main(String[] args) {
System.out.println("柱子: A B C");
System.out.println("作者 http://www.niuwanet.com/");
System.out.println("n = 3");
towers(3, 'A', 'C', 'B');
}
}
import java.util.Scanner;public class TowerOfHanoi
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
moveDisks(n,'A','B','C');
}
public static void moveDisks(int n,char fromTower,char toTower,char auxTower)
{
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);
}
}
}