读书笔记之汉诺塔变型题

编程入门 行业动态 更新时间:2024-10-23 23:33:23

<a href=https://www.elefans.com/category/jswz/34/1768764.html style=读书笔记之汉诺塔变型题"/>

读书笔记之汉诺塔变型题

汉诺塔问题增加条件:左边的塔到达右边的塔必须要经过中间的塔才可以


解题思路:

  1. 递归的方式 :如果只有一层塔的情况 以及n层塔的情况
  2. 使用堆栈的方式:考虑最佳的方式中 不能原路返回 以及上边的小于下边的要求

//使用栈的代码
package Charpter1;import java.util.Stack;public class hanoiProble2 {public static enum Action{No,LToM,MToL,MToR,RToM}public static int hanoiProble(int num,String left,String mid,String right){Stack<Integer> lS = new Stack<>();Stack<Integer> mS = new Stack<>();Stack<Integer> rS = new Stack<>();lS.push(Integer.MAX_VALUE);mS.push(Integer.MAX_VALUE);rS.push(Integer.MAX_VALUE);for (int i=num;i>0;i--){lS.push(i);}Action[] record ={Action.No};int step=0;while(rS.size() != num+1){step+=fStackToStack(record,Action.MToL,Action.LToM,lS,mS,left,mid);step+=fStackToStack(record,Action.LToM,Action.MToL,mS,lS,mid,left);step+=fStackToStack(record,Action.RToM,Action.MToR,mS,rS,mid,right);step+=fStackToStack(record,Action.MToR,Action.RToM,rS,mS,right,mid);}return step;}public static int fStackToStack(Action [] record,Action preNoAct,Action nowAct,Stack<Integer> fStack,Stack<Integer> tStack,String from,String to){if(record[0] !=preNoAct && tStack.peek()>fStack.peek()){tStack.push(fStack.pop());System.out.println("Move " + tStack.peek() + "from "+from +"to"+to);record[0]=nowAct;return 1;}return 0;}public static void main(String [] args){System.out.println(hanoiProble(2,"left","mid","rigth"));}
}

更多推荐

读书笔记之汉诺塔变型题

本文发布于:2024-02-25 02:54:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1697547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:读书笔记   变型   汉诺

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!