用栈来求解汉诺塔变形问题
生活随笔
收集整理的這篇文章主要介紹了
用栈来求解汉诺塔变形问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package stackAndQueue;import java.util.Stack;/*** 用棧來(lái)求解漢諾塔問(wèn)題:HanoiStack【3】* * 【問(wèn)題描述】:將漢諾塔游戲(小壓大)規(guī)則修改,不能從左(右)側(cè)的塔直接移到右(左)側(cè),而是必須經(jīng)過(guò)中間塔。* * 求當(dāng)塔有N層時(shí),打印最優(yōu)移動(dòng)過(guò)程和最優(yōu)移動(dòng)步數(shù)。如N=2,記上層塔為1,下層為2.則打印:1:left->mid;1* * 由于必須經(jīng)過(guò)中間,實(shí)際動(dòng)作只有4個(gè):左L->中M,中->左,中->右R,右->中。* * 原則:①小壓大;②相鄰不可逆(上一步是L->M,下一步絕不能是M->L)* * 非遞歸方法核心結(jié)論:1.第一步一定是L-M;2.為了走出最少步數(shù),四個(gè)動(dòng)作只可能有一個(gè)不違反上述兩項(xiàng)原則。* * 核心結(jié)論2證明:假設(shè)前一步是L->M(其他3種情況略)* * a.根據(jù)原則①,L->M不可能發(fā)生;b.根據(jù)原則②,M->L不可能;c.根據(jù)原則①,M->R或R->M僅一個(gè)達(dá)標(biāo)。* * So,每走一步只需考察四個(gè)步驟中哪個(gè)步驟達(dá)標(biāo),依次執(zhí)行即可。* * @author xiaofan*/
public class HanoiStack {private enum Action {None, LToM, MToL, MToR, RToM};static Action preAct = Action.None; // 上一步操作,最初什么移動(dòng)操作都沒(méi)有final static int num = 4; // 漢諾塔層數(shù)public static void main(String[] args) {int steps = transfer(num);System.out.println("It will move " + steps + " steps.");}private static int transfer(int n) {Stack<Integer> lS = new Stack<>(); // java7菱形用法,允許構(gòu)造器后面省略范型。Stack<Integer> mS = new Stack<>();Stack<Integer> rS = new Stack<>();lS.push(Integer.MAX_VALUE);// 棧底有個(gè)最大值,方便后續(xù)可以直接peek比較mS.push(Integer.MAX_VALUE);rS.push(Integer.MAX_VALUE);for (int i = n; i > 0; i--) {lS.push(i);// 初始化待移動(dòng)棧}int step = 0;while (rS.size() < n + 1) {// n+1,因?yàn)閞S.push(Integer.MAX_VALUE);等于n+1說(shuō)明全部移動(dòng)完成step += move(Action.MToL, Action.LToM, lS, mS);// 第一步一定是LToMstep += move(Action.LToM, Action.MToL, mS, lS);// 只可能有這4種操作step += move(Action.MToR, Action.RToM, rS, mS);step += move(Action.RToM, Action.MToR, mS, rS);}return step;}/*** 實(shí)施移動(dòng)操作.* * @param cantAct* 不能這樣移動(dòng)* @param nowAct* 即將執(zhí)行的操作* @param fromStack* 起始棧* @param toStack* 目標(biāo)棧* @return step(成功與否)*/private static int move(Action cantAct, Action nowAct, Stack<Integer> fromStack, Stack<Integer> toStack) {if (preAct != cantAct && toStack.peek() > fromStack.peek()) {toStack.push(fromStack.pop()); // 執(zhí)行移動(dòng)操作System.out.println(toStack.peek() + ":" + nowAct);preAct = nowAct; // 更新“上一步動(dòng)作”return 1;}return 0;}
}
代碼地址:https://github.com/zxiaofan/Algorithm/tree/master/src/stackAndQueue
總結(jié)
以上是生活随笔為你收集整理的用栈来求解汉诺塔变形问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spark入门实战系列--2.Spark
- 下一篇: Unity-Animator在Edito