C++ implementation of hannotta algorithm classic example
- 2020-04-02 02:29:36
- OfStack
This paper describes a classical C++ code implementation method for hannotta algorithm.
Hanotta problem description: the three columns are a, b, and c. The disk is initially in column a and moves to column c by means of column b. You need to specify the number of disks.
The specific implementation code is as follows:
#include <iostream>
using namespace std;
int times = 0; //Global variable, number of moves
//The NTH disk moves from column x to column z
void move(int n, char x, char z)
{
cout << " The first " << ++times << " step : will " << n << " Number plate from " << x << " Move to the " << z << endl;
}
//Move n disks numbered 1 to n from small to large according to diameter on x column to z column according to rules. Y is used as an auxiliary column
void hanoi(int n, char x, char y, char z)
{
if (n == 1)
move(1, x, z); //Move the 1 disk from x to z
else {
hanoi(n - 1, x, z, y); //Move the disks numbered 1 to n-1 on x to y, with z as the auxiliary column
move(n, x, z); //Move the n disk from x to z
hanoi(n - 1, y, x, z); //Move the disks numbered 1 to n-1 on y to z, with x as the auxiliary column
}
}
int main()
{
int n;
cout << "3 A column for a , b , c The disk was originally in a Column, with the aid of b The column to c The column. Please enter the number of disks: ";
cin >> n;
hanoi(n, 'a', 'b', 'c');
system("pause");
return 0;
}