A detailed illustration of the "Hanoi Tower Algorithm"

Hello, hello, I’m the little gray ape, a programmer who can write bugs,

Today I will share with you a case of a recursive classic algorithm --- "Hanoi Tower".

Review of the Tower of Hanoi

The Tower of Hanoi (Tower of Hanoi) is derived from Indian legends. When the Great Brahma created the world, he built three diamond pillars, one of which is stacked with 64 golden discs from the bottom up. The Great Brahma ordered the Brahmin to re-place the disc on another pillar in order of size from below. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.

This is a well-known problem, and almost all textbooks have an introduction to this problem . Because the conditions are :

With the help of a transfer column, the plates arranged in the starting column according to the rules are moved to the end column, and only one plate can be moved at a time, and the large plate is not allowed to be placed on the small plate, so the number of moves for 64 plates is: 18,446,744,073,709,551,615

This is an astronomical figure. If it is possible to calculate (and not output) a movement every microsecond, it would also take almost one million years. We can only find a solution to the problem and solve the Tower of Hanoi when the value of N is small, but it is difficult to solve the 64-story Tower of Hanoi with a computer.

In ordinary programming exercises, the Tower of Hanoi problem is also a very common algorithm case. Today, I will analyze the solution to the Tower of Hanoi problem with my friends.

First, let’s take a look at a diagram of a three-layered Hanoi Tower to have a simple understanding of the solution to the Hanoi Tower problem:

 

As shown in the figure above, we can see that when the number of plates is only one, we can directly move the plates to the target plate to solve the three-layer Hanoi Tower problem. We first move the top two plates to the middle carousel with the help of the target plate, then move the largest plate to the target plate, and then move the first plate on the middle carousel to the starting plate, this time we can move Move the second disk to the target disk, and finally move the first disk on the starting disk to the target disk.

From this we can summarize the solution of the n-layer Hanoi Tower:

Move the first n-1 trays to the adjacent empty tray with the help of the current transfer tray (not necessarily tray B), then move the nth tray to the target tray, and then repeat the above steps until all trays are moved To the target disk. The recursive idea of ​​the function method is also used here.

 

Next, use java and Python to demonstrate the solution method of the n-order Hanoi Tower:

Java solves the Tower of Hanoi

package 汉诺塔算法;


public class Hanoi {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Hanoi h = new Hanoi();
		char a = 'A';
		char b = 'B';
		char c = 'C';
		int count = h.hanoi(3, a, b, c);
		System.out.println(count);
	}
	
	/**
	 * 汉诺塔问题
	 * @param n 阶数
	 * @param a 起始柱
	 * @param b 中转柱
	 * @param c 目标柱
	 * @return 移动次数
	 * */
	public int hanoi(int n,char a,char b,char c) {
		if (n == 1) {
			move(a, c);
		} else {
			hanoi(n-1, a, c, b);
			move(a, c);
			hanoi(n-1, b, a, c);
		}
		//汉诺塔的移动次数为(2**n)-1
		return (int) Math.pow(2, n)-1;
	}
	
	public void move(char a,char b) {
		System.out.println(a + "--->" + "b");
	}
}

Python solves the Tower of Hanoi

i = 1   # 定义全局变量记录次数
def move(n, a, c):
    global i
    print("第{}步:将编号为{}的盘子从{}--->{}".format(i, n, a, c))
    i += 1
def hanoi(n,a,b,c):
    #a,b,c分别是三根柱子,n为套在a柱上的圆圈个数
    if n == 1:
        move(n, a, c)
    else:
        hanoi(n-1, a, c, b)
        move(n, a, c)
        hanoi(n-1, b, a, c)
if __name__ == '__main__':
    n = int(input("请输入盘子数量:"))
    hanoi(n, "A", "B", "C")

Well, I will share the explanation about the Tower of Hanoi with my friends here. If there are any deficiencies, I hope everyone can make corrections. The Big Bad Wolf will accompany you to make progress together!

Guess you like

Origin blog.csdn.net/weixin_44985880/article/details/111416152