import javax.swing.JOptionPane; public class hanoitower { /** * @param args */ public static void main(String[] args) { //read number of disks,n String intString=JOptionPane.showInputDialog("Enter number of disks:"); int n=Integer.parseInt(intString); moveDisks(n,'A','B','C'); } /**The method for finding the solution to move n disks * form fromTower to toTower with auxTower */ public static void moveDisks(int n,char fromTower,char toTower,char auxTower){ if(n==1)//stopping condition System.out.println("move Disks"+" "+n+" form"+" "+fromTower+" to"+" "+toTower); else{ moveDisks(n-1,fromTower,auxTower,toTower); System.out.println("move Disks "+n+" form "+fromTower+" to "+toTower); moveDisks(n-1,auxTower,toTower,fromTower);
if (n == 1)
System.out.println("move " + startpeg + " to " + endpeg);
else {
hanoi(n - 1, startpeg, endpeg, middlepeg);
System.out.println("move " + startpeg + " to " + endpeg);
hanoi(n - 1, middlepeg, startpeg, endpeg);
}
} public static void main(String[] args) {
int n = 3;
String startpeg = "start";
String middlepeg = "middle";
String endpeg = "end";
System.out.println("The solution for n = " + n); hanoi(n, startpeg, middlepeg, endpeg);
}
}找的
public class hanoitower { /**
* @param args
*/
public static void main(String[] args) {
//read number of disks,n
String intString=JOptionPane.showInputDialog("Enter number of disks:");
int n=Integer.parseInt(intString);
moveDisks(n,'A','B','C');
}
/**The method for finding the solution to move n disks
* form fromTower to toTower with auxTower
*/
public static void moveDisks(int n,char fromTower,char toTower,char auxTower){
if(n==1)//stopping condition
System.out.println("move Disks"+" "+n+" form"+" "+fromTower+" to"+" "+toTower);
else{
moveDisks(n-1,fromTower,auxTower,toTower);
System.out.println("move Disks "+n+" form "+fromTower+" to "+toTower);
moveDisks(n-1,auxTower,toTower,fromTower);
}
}}