6 Use stack to solve the three-column Hanoi Tower problem

Keywords: less


When N layers are found for the three-column Hanoi Tower, the optimal moving process and the optimal total moving steps are printed.The restriction cannot be moved directly from the leftmost tower to the rightmost, nor from the rightmost to the leftmost, but must go through the middle.


The modified Hannotta problem has only four actual actions:'Left'to'Middle','Middle' to'Left','Middle'to'Right','Right' to'Middle'.

There are two prerequisites for an action to occur:

  1. Do not violate the principle of small pressure: the element num that pops up from the front stack must have a value less than the top of the current to stack if it is to be pushed into the to stack.
  2. Neighborhood irreversibility principle: If you want to go out of the minimum number of steps, no two adjacent actions are reciprocal.

Based on the above two principles, two conclusions can be deduced:

  1. The first action must be L->M.
  2. At any moment in the process of walking out of the minimum number of steps, only one of the four actions does not violate the above two principles, and the other three actions must be violated.
code implementation
//Tri-column Hanoi Tower, which stipulates that it can only move between adjacent columns at a time
public class HanoiProblem {
    public enum Action {
        No, LToM, MToL, MToR, RToM

    public int hanoiProblem(int num, String left, String mid, String right) {
        Stack<Integer> lS = new Stack<>();
        Stack<Integer> mS = new Stack<>();
        Stack<Integer> rS = new Stack<>();

        for (int i = num; i > 0; i--) {
        Action[] record = {Action.No};
        int step = 0;

        while (rS.size() != num + 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()) {
            System.out.println("Move " + tStack.peek() + " from " + from + " to " + to);
            record[0] = nowAct;

            return 1;

        return 0;

    public static void main(String[] args) {
        HanoiProblem hanoi = new HanoiProblem();

        System.out.println("Solve the minimum number of steps for a three-layer Hannotta:" + hanoi.hanoiProblem(3, "left", "mid", "right"));

Posted by b0ksah on Mon, 02 Dec 2019 02:03:22 -0800