汉诺塔算法

阅读更多
import java.util.*;


public class HanoiTask {
    class Tower {
       private int number;
       private String name;
       private Stack stack = new Stack();
       
       public Tower(int number,String name) {
           this.number = number;
           this.name = name;
       }
              
       public int getNumber() {
           return number;
       }
 
       public String getName() {
           return name;
       }
 
       public Stack getStack() {
           return stack;
       }
       
    }
    
    class Tray {
       private int number;
       private String name;
       
       public Tray(int number,String name) {
           this.number = number;
           this.name = name;
       }
       
       public int getNumber() {
           return number;
       }
       
       public String getName() {
           return name;
       }
       
       public String toString() {
           return name;
       }
    }
    
    public static   void hanoi(int num,Tower from,Tower middle,
           Tower to, List result) {
       if(num == 1) {
           move(from,middle,to, result);
       } else {
           hanoi(num-1,from,to,middle, result);
           move(from,middle,to, result);
           hanoi(num-1,middle,from,to, result);
       }
    }
    
    private static  void move(Tower from,Tower middle ,Tower to, List result) {
       E tray = from.getStack().pop();
       to.getStack().push(tray);
       result.add(from.getName()+to.getName());
    }
	
    public static List transferFromAtoC(int n) {
    	List result = new ArrayList();
    	HanoiTask t = new HanoiTask();
    	Tower from = t.new Tower(1, "A");
        Tower middle = t.new Tower(2, "B");
        Tower to = t.new Tower(3, "C");
        
        int num = n;
        for (int i = num; i >0; i--) {
            Tray tray = t.new Tray(i,i+"");
            from.getStack().push(tray);
        }
        hanoi(num, from, middle, to, result);
        return result;
    }
    
}
  • Hanoi.zip (1 KB)
  • 下载次数: 0

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