汉诺塔递归算法
import java.util.Scanner;
public class hannuota {
public void key(int n,String A,String B,String C){
if(n==1){
System.out.println("将"+n+"从"+A+"移至"+C);
}else{
key(n-1, A, C, B);
System.out.println("将"+n+"从"+A+"移至"+C);
key(n-1,B,A,C);
}
}
public static void main(String[] args) {
hannuota hannuota = new hannuota();
System.out.println("请输入汉诺塔规模:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("请输入汉诺塔序号:");
Scanner sc1 = new Scanner(System.in);
String first = sc1.nextLine();
System.out.println("请输入汉诺塔序号:");
Scanner sc2 = new Scanner(System.in);
String second = sc2.nextLine();
System.out.println("请输入汉诺塔序号:");
Scanner sc3 = new Scanner(System.in);
String third = sc3.nextLine();
hannuota.key(n,first,second,third);
}
}
|