汉诺塔是递归算法里的一个经典案例,有三根柱子A,B,C,A柱子上有N个盘子,从小到大依次叠放,要求把A上的盘子都移到C上,B可以作为临时存放,移动的时候必须始终遵循小盘子在大盘子上面,且每次只能移动一个盘子,求其算法。用java实现如下:
下面的链接是个flash
[url]http://www.sznews.com/jbjob/content/2007-09/17/content_1514108.htm[/url]
public class Hanoi{
public static void main(String[] args){
moveAll(4,'A','B','C');
}
//参数 n表示移动n个盘子,from 表示本来放盘子的,temp是临时存放盘子的,to是最终目的
public static void moveAll(int n,char from,char temp,char to){
if(n==1){
move(n,from,to);
}else{
moveAll(n-1,from,to ,temp);//要移动n个盘子首先要将n-1个盘子借助to,移到temp上,然后才能将最大的那个盘子放到to上
move(n,from,to);//将最大的第n个盘子从from 移到to上
moveAll(n-1,temp,from,to);//最后再将n-1个盘子由temp,借助from,移动到to上
}
}
//移动第n个盘子
public static void move(int n,char from,char to){
System.out.println("move "+n +" from " + from +" to "+ to);
}
}
下面的链接是个flash
[url]http://www.sznews.com/jbjob/content/2007-09/17/content_1514108.htm[/url]