学习 · 2005年12月13日 0

河内塔解决方案

import javax.swing.JOptionPane;
public class TowersOfHanoi {
/**
* @param args
*TowersOfHanoi.java :find solutions for the Towers of Hanoi problem
*by etc4.com
*/
public static void main(String[] args) {
// read number of disks ,n
String intString = JOptionPane.showInputDialog(null,”enter number of disks:”,
“TowersOfHanoi Input”,JOptionPane.QUESTION_MESSAGE);
//covert string into integer
int n = Integer.parseInt(intString);
//find the solutions recursively
System.out.println(“The moves are: “);
moveDisks(n,’A’,’B’,’C’);
System.exit(0);
}
/**the method for finding the solution to move n disks from fromTower to toTower
*with auxTower*/
public static void moveDisks(int n,char fromTower,char toTower,char auxTower){
if(n==1)//stoping condition
System.out.println(“Move disk “+ n +” from ” + fromTower + ” to ” + toTower);
else{
moveDisks(n-1,fromTower,auxTower,toTower);
System.out.println(“Move disk “+ n +” from ” + fromTower + ” to ” + toTower);
moveDisks(n-1,auxTower,toTower,fromTower);
}
}
}