[Algorithm] Tower of Hanoi

topic:

Input the number of floors n of the Tower of Hanoi, print the steps of moving the n-story tower body from stick a to stick b to stick c, and output the total number of moves

The structure of the Tower of Hanoi is that the area of ​​the upper floors of the tower must be smaller than that of the lower floors, and only one floor of the tower can be moved at a time, and this principle is followed every time it is moved

multiple input

algorithm:

Using recursive thinking, to move the n-story tower body from stick a to stick c by using stick b, first move the tower body of n-1 floors to stick b through stick c, and then move the last layer directly to stick c (with the largest area layer), and finally move the n-1 layer on the b stick to the c stick through the a stick

source code:

#include <iostream>
using namespace std;

int g_count = 0;

void Move(char a, char b)
{
	cout << a << " -> " << b << endl;
	++g_count;
}


// a柱借助b柱将n个木块移到c柱
void Hnoi(char a, char b, char c, int n)
{
	if (n == 1)
		Move(a, c);
	else
	{
		Hnoi(a, c, b, n - 1);
		Move(a, c);
		Hnoi(b, a, c, n - 1);
	}
}

int main()
{
	int n;
	cin >> n;

	Hnoi('A', 'B', 'C', n);
	cout << "the step count is : " << g_count << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/phoenixFlyzzz/article/details/130438825