题解 | #用栈来求解汉诺塔问题#

用栈来求解汉诺塔问题

https://www.nowcoder.com/practice/1a2f618b3433487295657b3414f4e7c4

import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        String[] move = {"no", "LM", "ML", "MR", "RM"};
        Scanner in = new Scanner(System.in);
        int level = in.nextInt();

        Stack<Integer> l = new Stack<>();
        Stack<Integer> m = new Stack<>();
        Stack<Integer> r = new Stack<>();
        l.push(Integer.MAX_VALUE);
        m.push(Integer.MAX_VALUE);
        r.push(Integer.MAX_VALUE);
        for(int i = level; i > 0; i--) {
            l.push(i);
        }
        int res = 0;
        String[] lastMove = {move[0]};
        while(r.size() < level + 1) {
            res += moveStack(l, m, lastMove, move[1], move[2], "left", "mid");
            res += moveStack(m, l, lastMove, move[2], move[1], "mid", "left");
            res += moveStack(m, r, lastMove, move[3], move[4], "mid", "right");
            res += moveStack(r, m, lastMove, move[4], move[3], "right", "mid");
        }
        System.out.println("It will move " + res + " steps.");
    }

    private static int moveStack(Stack<Integer> fromS, Stack<Integer> toS, String[] lastMove, String move, String reverseMove, String from, String to) {
        if(lastMove[0].equals(reverseMove) || fromS.size() == 1 || fromS.peek() > toS.peek()) {
            return 0;
        }
        System.out.println("Move " + fromS.peek() + " from " + from + " to " + to);
        toS.push(fromS.pop());
        lastMove[0] = new String(move);
        
        return 1;
    }
}

全部评论

相关推荐

被普调的六边形战士很高大:项目经历貌似和专业或者求职方向没大关系?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务