[Algorithm diary] Recursive realization of the Tower of Hanoi

Problem description : The
Tower of Hanoi: The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy derived from an ancient legend in India. When Brahma created the world, he made three diamond pillars. On one pillar, 64 golden discs were stacked in order of size from bottom to top. The Brahma ordered the Brahmin to re-place the disc on another pillar in order of size from below. It also stipulates that the disk cannot be enlarged on the small disk, and only one disk can be moved at a time between the three pillars. (That is: the small plate must be on top of the large plate, and only one plate can be moved at a time. Finally, all the plates above A are moved to C)
Insert picture description here

Thought : Assuming there are two plates now, you can directly move the small plate from A to B, then move the large plate from A to C, and finally move the small plate from B to C. In fact, 64 plates are the same. You can think of the top 63 plates as a whole, first move the 63 plates from A to B, then move the bottom plate from A to C, and then move the 63 plates from B to C. How to move the 63 plates? Take the above 62 as a whole. . . By analogy, it is actually recursion, down to the simplest case.

#include <cassert>
using namespace std;
#define length 3
#include<iostream>
using namespace std;
int main()
{
	void hanoi(int n, char one, char two, char three);
	int m;
	cout << "输入盘子数:";
	cin >> m;;
	hanoi(m, 'A', 'B', 'C');
}


void hanoi(int n, char one, char two, char three)
{
	void move(char x, char y);
	if (n == 1)
	{
		move(one, three);//递归结束条件。此时只有一个盘子
	}
	else
	{
		hanoi(n - 1, one, three, two);//将上面n-1个盘子从A移动到B,(可以借助C)
		move(one, three);//输出
		hanoi(n - 1, two, one, three);将上面n-1个盘子从B移动到C(借助A)
	}
}

Guess you like

Origin blog.csdn.net/wdxyxshark/article/details/108713359