当前位置: 代码迷 >> 综合 >> JAVA-汉诺塔问题(hanoi)
  详细解决方案

JAVA-汉诺塔问题(hanoi)

热度:24   发布时间:2023-11-26 05:26:23.0

JAVA-汉诺塔问题(hanoi)

import java.util.Scanner;public class Hanoi_1 {int sum = 0;public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("Enter numbers of disks : ");int n = sc.nextInt();Hanoi_1 Han = new Hanoi_1();char A='A',B='B',C='C';Han.Hanoi(n,A,B,C);System.out.println("最终移动次数:"+Han.sum);}void move(char A,int n,char C){sum++;System.out.println("第"+sum+"次移动"+" move disk"+n+" from "+A+" to "+C);}void Hanoi(int n,char A,char B,char C) {if(n == 1)move(A,1,C);else{Hanoi(n-1,A,C,B);   //将A上标号为1至n-1的圆盘移到B,C做辅助塔move(A,n,C);    //将编号为n的圆盘从A移到CHanoi(n-1,B,A,C);}}
}

  相关解决方案