Solve the Tower of Hanoi problem recursively (C++)

Solve the Tower of Hanoi problem recursively (C++)

[Problem description]
Hanoi Tower problem. This is a classic mathematical problem: there was a Vatican Pagoda in ancient times. There were 3 seats A, B, and C in the tower. At the beginning, there were 64 plates on the A seat. An old monk wanted to move these 64 plates from Block A to Block C, but only one plate was allowed to be moved at a time, and during the movement, the three plates always kept the big plate on the bottom and the small plate on the top. Block B can be used in the process of moving E, and it is required to write a program to print out the moving steps if there are only n plates.

[Problem Analysis]
1. Assuming that there are n plates on Block A at the beginning, if we can move the bottom plate to Block C through Block B, we only need to add all the n-1 plates on Block A Just move to Block C.
2. To move the bottom plate to Block C, you must first move the upper n-1 plates to Block B through Block C, and then move the largest plate directly to Block C.
3. Then move the n-1 plates on the B seat to the C seat through the A seat, so that a recursion is realized.

【Code】

#include <iostream>
using namespace std;
int main()
{
    
    
	void hnt(int n,char a,char b,char c);
	int num;
	char a,b,c;
	a='A';
	b='B';
	c='C'; 
	cin>>num;
	hnt(num,a,b,c);
	return 0;
}
void hnt(int n,char a,char b,char c)
{
    
    
	if(n==1) cout<<a<<"--->"<<c<<endl;
	else
	{
    
    hnt(n-1,a,c,b);
	hnt(1,a,b,c);
	hnt(n-1,b,a,c);
	}
}

If it is required to number the plates again, the implementation code is as follows:

#include <iostream>
using namespace std;
void Move(int n,char x,char y)
{
    
    
   cout<<x<<"->"<<n<<"->"<<y<<endl;
}
void Hannoi(int n,char a,char c,char b)
{
    
    
	if(n==1) Move(1,a,b);
    else
    {
    
    Hannoi(n-1,a,b,c);
    Move(n,a,b);
    Hannoi(n-1,c,a,b);
    }
}
int main()
{
    
    
	int n;
	char a,b,c;
  	cin>>n>>a>>b>>c;
    Hannoi(n,a,c,b);
    return 0;
}

Guess you like

Origin blog.csdn.net/hyl1181/article/details/107494798