import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Hanio{
private List<Integer> xl = new LinkedList<Integer>();//3个链表当作hanio塔的3个轴
private List<Integer> yl = new LinkedList<Integer>();
private List<Integer> zl = new LinkedList<Integer>();
private char x,y,z;//3个轴的名称
private int count;//总盘子数
private Map<Character,List<Integer>> map = new HashMap<Character, List<Integer>>();
public void init(int count,char x,char y,char z){//初始化
this.count = count;
int i = count;
while(i>0){
xl.add(i--);
}
this.x = x;
this.y = y;
this.z = z;
map.put(x, xl);
map.put(y, yl);
map.put(z, zl);
}
public void run(){
System.out.println("开始情况:");
show();
move(count,x,y,z);
}
public void move(int count,char x,char y,char z){//递归移动
if(count==1){//当仅仅有一个圆盘的时候,直接将其从x移动到z
System.out.println("将第"+count+"个从"+x+"移动到"+z);
moveL(count,map.get(x),map.get(z));
}else{//>1个圆盘的时候
move(count-1,x,z,y);//将头count-1个从x移动到y,这样空出了第count个,直接将这一个x移动到z
System.out.println("将第"+count+"个从"+x+"移动到"+z);
moveL(count,map.get(x),map.get(z));
move(count-1,y,x,z);//将y上的count-1个移动到z
}
}
private void moveL(int num,List a,List b){//将第num个盘子从a移动到b
a.remove(new Integer(num));
b.add(new Integer(num));
show();
}
private void show(){//显示
int xLen = xl.size();
int yLen = yl.size();
int zLen = zl.size();
int max = xLen>yLen?xLen:yLen;//取这3个当中的最大值
max = max>zLen?max:zLen;
for(int i = max-1; i>-1; i--){
if(i < xLen){
System.out.print(xl.get(i)+" ");
}else{
System.out.print(" ");
}
if(i < yLen){
System.out.print(yl.get(i)+" ");
}else{
System.out.print(" ");
}
if(i < zLen){
System.out.print(zl.get(i));
}
System.out.println();
}
System.out.println(x+" "+y+" "+z);
}
public static void main(String[] args){
Hanio h = new Hanio();
h.init(3, 'a', 'b', 'c');
h.run();
}
}
执行的结果: