在线编程--汉诺塔问题
2016-04-03 16:39
399 查看
题目描述
对于传统的汉诺塔游戏我们做一个拓展,我们有从大到小放置的n个圆盘,开始时所有圆盘都放在左边的柱子上,按照汉诺塔游戏的要求我们要把所有的圆盘都移到右边的柱子上,请实现一个函数打印最优移动轨迹。
给定一个int n,表示有n个圆盘。请返回一个string数组,其中的元素依次为每次移动的描述。描述格式为: move from [left/mid/right] to [left/mid/right]。
测试样例:
1
返回:move from left to right
对于传统的汉诺塔游戏我们做一个拓展,我们有从大到小放置的n个圆盘,开始时所有圆盘都放在左边的柱子上,按照汉诺塔游戏的要求我们要把所有的圆盘都移到右边的柱子上,请实现一个函数打印最优移动轨迹。
给定一个int n,表示有n个圆盘。请返回一个string数组,其中的元素依次为每次移动的描述。描述格式为: move from [left/mid/right] to [left/mid/right]。
测试样例:
1
返回:move from left to right
import java.util.*; public class Hanoi { static ArrayList<String> arr=new ArrayList<String>(); public ArrayList<String> getSolution(int n) { // write code here String left="left"; String mid="mid"; String right="right"; hanoiProblems(n,left, mid, right); return arr; } public enum Action{ No,LToM,MToL,MToR,RToM } public int hanoiProblems(int n,String left,String mid,String right){ Stack<Integer> ls=new Stack<Integer>(); Stack<Integer> ms=new Stack<Integer>(); Stack<Integer> rs=new Stack<Integer>(); ls.push(Integer.MAX_VALUE); ms.push(Integer.MAX_VALUE); rs.push(Integer.MAX_VALUE); for(int i=n;i>0;i--){ ls.push(i); //将数字压入栈内 } Action[] record={Action.No}; int step=0; while(rs.size()!=n+1){ step+=fStackTotStack(record, Action.MToL, Action.LToM, ls, ms, left, mid); step+=fStackTotStack(record, Action.LToM, Action.MToL, ms, ls, mid, left); step+=fStackTotStack(record, Action.RToM, Action.MToR, ms, rs, mid, right); step+=fStackTotStack(record, Action.MToR, Action.RToM, rs, ms, right, mid); } return step; } public static int fStackTotStack(Action[] record,Action preNoAct,Action nowAct,Stack<Integer> fStack,Stack<Integer> tStack, String from,String to){ if(record[0]!=preNoAct&&fStack.peek()<tStack.peek()){ tStack.push(fStack.pop()); arr.add("Move "+tStack.peek()+" from "+from+" to "+to); record[0]=nowAct; return 1; } return 0; } }
相关文章推荐
- 【Java】求系统当前时间
- ASP.NET MVC EF 02 数据库访问层的设计
- python爬虫(爬取糗事百科段子)_get_text() , 文件写入
- Struts2环境搭建
- java虚拟机HotSpot中的垃圾收集器
- java学习笔记(五)
- Java对XML文档的解析
- PHP magic_quotes_gpc的详细使用方法
- 与时俱进的Java——《写给大忙人看的Java核心技术》
- Okttp3.0简单的二次回调封装
- RxJava-创建Observable操作符
- Git托管代码
- JAVA虚拟机-JVM性能调优(五)
- Kafka集群搭建及简单使用(控制台与Java客户端)
- ffmpeg-php扩展的安装与使用方法
- Java学习之ACM相关基础知识
- NYOJ 16 矩形嵌套
- [Java]不同包的类之间的继承
- 第五章 springboot + mybatis
- J2EE 日志错误