Hanoi problem (Hanoi) C language and Python implementation

Topic and analysis:

  • Intercepted from C language books, detailed topic description and problem-solving analysis
    Insert picture description here
    Insert picture description here
    Insert picture description here
    Insert picture description here

C language implementation:

  • I tried to solve the problem by myself, but I still couldn't figure it out very well.
  • To sum up, there are two main points
  • (1) To discover the law, think about using recursion, and then how to code to achieve recursion
  • (2) The ABC described in it has three towers and two processes, (1) A uses B to C, (2) B uses A to C. Both can be abstracted as a relationship between one and the other with the help of the other~ This also abstracts the two situations into one, and one function solves it. I did not expect this

Below is the problem-solving code in the book

// 汉诺塔问题
#include<stdio.h>

int main()
{
    
    
	void hanoi(int n, char one, char tow, char three);
	int m;
	printf("请输入要移动的盘子数目\n");
	scanf("%d", &m);
	printf("这是移动盘子的步骤:\n");
	hanoi(m, 'A', 'B', 'C');

	return 0;
}

// 实现将 one 借助 tow 转移到 three
void hanoi(int n, char one, char tow, char three)
{
    
    
	void move(char c1, char c2);
	// 当只有一个盘子的时候
	if(n == 1)
	{
    
    
		move(one , three);
	}
	else
	{
    
    
		//递归
		//1. n-1 个盘子,移动到 B, 此时: A 借助 C 向 B 移动
		hanoi(n-1, one, three, tow);
		//2. n个盘子还剩最下面一个,就直接放到C, 此时: A直接放到C
		move(one, three);
		//3. 再将 n-1个移动到B的盘子 移动到 C, 此时 B 借助 A 向 C移动
		hanoi(n-1, tow, one, three);

	}
}

// 用这个函数输出移动的步骤
void move(char c1, char c2)
{
    
    
	printf("%c-->%c\n",c1,c2);
}
  • I have done a simple recursion before. This surprising and expanded thinking is that the else calls itself multiple times and completes the goal once in three steps . This is a bit more complicated than imagined single call.

Python implementation

  • Similarly, there is no new method in Python, and it is rewritten into Python code according to the above logic.
x = int(input("请输出盘子的数量"))

def hanoi(n, one, tow, three):
    if n == 1:
        move(one, three)
    else:
        hanoi(n-1, one, three, tow)
        move(one, three)
        hanoi(n-1, tow, one , three)

def move(c1, c2):
    print("%c-->%c" % (c1, c2))

hanoi(x, 'A', 'B', 'C')

Overall, this topic has given me a lot of gains. The first to understand the function of a function, solve the problem in the recursion of a function.

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/112862481