问题描述:
简单分析:
一个盘子:只需form A to C;
两个盘子:1、盘子1form A to B ;2、盘子2 form A to C;3、盘子2 form B to C;
代码:
package 递归;
import java.util.Scanner;
public class Hanoi {
public void exchange(int n, char a, char b, char c){
if(n == 1){
System.out.println("The " + n + " from " + a + " to " + c);
}else{
exchange(n-1, a, c, b);
System.out.println("The " + n + " from " + a + " to " + c);
exchange(n-1, b, a, c);
}
}
public static void main(String[] args) {
System.out.println("请输入一个数:");
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Hanoi hanoi = new Hanoi();
hanoi.exchange(N, 'a', 'b', 'c');
}
}
测试结果: