Java recursively implements the Tower of Hanoi game

Java recursively implements the Tower of Hanoi game

1. Rules

The Tower of Hanoi is a classic math problem that involves moving a stack of plates from a starting pillar to another goal pillar while doing so with the help of an intermediate pillar. The following are the rules of the Tower of Hanoi:

  1. There are three pillars, called the starting pillar, the goal pillar and the intermediate pillar.
  2. Initially, all plates are stacked on the starting column in order from largest to smallest.
  3. Only one plate can be moved at a time, and only smaller plates can be placed on top of larger plates.
  4. During the movement, the plates can be temporarily stored with the help of the intermediate column.
  5. The goal is to move all the plates from the starting column to the target column.

2. Code implementation

(1) Ideas

According to the rules, the Tower of Hanoi problem can be solved using recursion. The steps of the recursive solution are as follows:

  1. If there is only one plate, move it directly from the starting column to the target column.
  2. If there are multiple plates, move the upper plates except the bottom one from the start column to the middle column (with the aid of the goal column).
  3. Move the bottommost plate from the starting column to the target column.
  4. Move the plate that was previously moved to the middle column from the middle column to the target column (with the help of the starting column).

By repeating the above steps, all the plates can be moved from the starting column to the target column, completing the movement of the Tower of Hanoi.

Note that the solution to the Towers of Hanoi problem has exponential time complexity, so it can become very time-consuming when dealing with a large number of plates.

(2) Code

public class MyClass {
    
    
   public static void main(String[] args){
    
    
       // 3 是塔的层数,a 是起始柱子,b 是中间柱,c 是目标柱
       tower(3, 'a', 'b', 'c');
   }

   //递归
   public static void tower(int num, char a, char b, char c) {
    
    
       //只有一个盘子时,直接将它从起始柱移动到目标柱
       if (num == 1) {
    
    
           System.out.println(a + " --> " + c);
       } else {
    
    
           //将除了最底下盘子以外的所有盘子视为一个,移动到中间柱
           tower(num - 1, a, c, b);
           //将最底下的盘子移动到目标柱
           System.out.println(a + " --> " + c);
           //将除了最底下盘子以外的所有盘子视为一个,移动到目标柱
           tower(num - 1, b, a, c);
       }
   }

}

(3) Complexity

  • Time complexity: O(2^n), where nis the number of plates.
  • Space Complexity: O(n). Because the recursive call will generate the overhead of the recursive stack, the depth of the recursion is n-1.

3. Running results

a --> c
a --> b
c --> b
a --> c
b --> a
b --> c
a --> c

Guess you like

Origin blog.csdn.net/qq_45256357/article/details/131965586