递归-汉诺塔
来源:互联网 发布:网络打印机显示错误 编辑:程序博客网 时间:2024/05/21 08:40
可以用递归实现,递归算法:
A source tower,B buffer tower ,C destination tower
1. Move the subtree consisting of the top n-1 disks from A to B.
2. Move the remaining (largest) disk from A to C.
3. Move the subtree from B to C.
Base Case:How do you move a subtree of two disks from A to C? Move the subtree consisting of only one disk (1) from A to B. This is the base case: When you’re moving only one disk, you just move it; there’s nothing else to do. Then move the larger disk (2) from A to C, and replace the subtree (disk 1) on it.
从A移动到C的过程如下:
柱子数据结构:用栈实现
class Tower{ pirvate Stack diskStack; private int index; //the current tower's index in the Towers arrary public Tower(i){ diskStack=new Stack();index=i; } public void add(int d){ if(!diskStack.isEmpty() && diskStack.peek()<=d){ System.out.println("Error placing disk " +d);}else diskStack.push(d); }//end add public int getIndex(){ return index; }//end getIndex()}//end class Tower
汉诺塔代码
public static void main(String[] args){ int diskNumber=5; //disks number int towerNumber=3; //tower number Tower[] towers=new Tower[3]; //initial tower's index in the towers' array for(int i=0;i<3;i++) towers[i]=new Tower(i); //initial towers[0] for(int i=diskNumber-1;i>=0;i--) towers[0].add(i); //move disk from 0 to 2 moveDisks(n,towers[0],towers[1],towers[2]); }//end mainpublic static moveDisks(int n,Tower from,Tower buffer,Tower to){ if(n==1) //base case moveTop(from,to); else{ moveDisks(n-1,from,to,buffer); //from A to BmoveTop(from,to);//from A to CmoveDisks(n-1,buffer,from,to);//from B to C }//end else}//end moveDisks()private static moveTop(Tower from,Tower to){ int top=from.pop(); to.add(top); System.out.println("Move disk "+top+" from "+ from.getIndex()+" to "+ to.getIndex() );}//end moveTop()
- 汉诺塔,递归&非递归
- 递归::汉诺塔
- 汉诺塔--递归
- 递归 -- 汉诺塔
- 汉诺塔(递归)
- 递归-汉诺塔
- 汉诺塔递归
- (递归)汉诺塔
- 汉诺塔-递归
- 汉诺塔:递归
- 汉诺塔 --递归
- 汉诺塔【递归】
- 递归-汉诺塔
- 递归汉诺塔
- 汉诺塔(递归)
- 递归汉诺塔
- 递归:汉诺塔
- 递归 & 汉诺塔
- 复杂的心情
- 函数索引
- hibernate中一对多等关系映射图和主键生成策略
- 【HTML】使用Iframe标签显示目标网页(内容)的某区域
- 购物车3种实现方式
- 递归-汉诺塔
- gerrit.config sample
- Objective-C语言学习之数据类型
- ss命令
- 在windowx下运行cygwin出行 bash-3.02$ (bash-2.05b$)等类似问题的解决办法:
- [zz]MFC - GetSystemMenu(FALSE)
- 微信的使用方法
- 如何制作一个横版格斗过关游戏 Cocos2d-x 2.0.4
- 用VisualStudio2005做简单的窗口程序