Java汉诺塔

import java.util.Scanner;

public class TowersofHanoi
{
     public static void main(String[] args)
     {
          Scanner input = new Scanner(System.in);
          System.out.print("Enter number of disks: ");
          int n = input.nextInt();
          
          System.out.println("The moves are: ");
          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);              
//将上面n-1个盘子从A搬到C
               System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower); //将第n个从A搬到B
               moveDisks(n-1,auxTower,toTower,fromTower);          
  //将C的n-1个从C搬到B
          } 
     }
}

你可能感兴趣的:(Java汉诺塔)