汉诺塔算法

import java.util.*;


public class HanoiTask {
    class Tower<E> {
       private int number;
       private String name;
       private Stack<E> stack = new Stack<E>();
       
       public Tower(int number,String name) {
           this.number = number;
           this.name = name;
       }
              
       public int getNumber() {
           return number;
       }
 
       public String getName() {
           return name;
       }
 
       public Stack<E> 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 <T>  void hanoi(int num,Tower<T> from,Tower<T> middle,
           Tower<T> to, List<String> 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 <E> void move(Tower<E> from,Tower<E> middle ,Tower<E> to, List<String> result) {
       E tray = from.getStack().pop();
       to.getStack().push(tray);
       result.add(from.getName()+to.getName());
    }
	
    public static List<String> transferFromAtoC(int n) {
    	List<String> result = new ArrayList<String>();
    	HanoiTask t = new HanoiTask();
    	Tower<Tray> from = t.new Tower<Tray>(1, "A");
        Tower<Tray> middle = t.new Tower<Tray>(2, "B");
        Tower<Tray> to = t.new Tower<Tray>(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;
    }
    
}

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