Tower of Hanoi (Hanoi Tower)

Tower of Hanoi (Hanoi Tower)

There are A, B, C three pillars, will move n disks A pillar to the C pillar, the title probably means this way, we should all know

The core idea: the n disks is divided into 2 parts, above the n-1 and a lowermost one, will move to the n-1 B plate disk, to move the cassette bottom plate C, and finally the n-1 a plate is moved to the C drive. There continues to repeat recursion: F (n) = F (n-1) × 2 +1

Baidu Encyclopedia there is another explanation, you can see each other on the shining:

When the plate number is n, the number of movements should be equal to 2 ^ n - 1 (interested can try to prove yourself). Later, an American scholar discovered an easy way to unexpected, as long as the turn to perform two operations on it. The first three columns sequenced shaped finished, all the disks in descending order on column A, the order of columns is determined according to the number of the discharge disc: if n is an even number, sequentially clockwise placing the ABC;
if n is odd, clockwise sequentially placed ACB.
⑴ clockwise movement of the disc 1 from the current column to the next one column, i.e., when n is even, if the disk 1 in column A, B to put it moves; if a disc 1 in column B, put it moves to the C; if the disk 1 in column C, it moves to put A.
⑵ Subsequently, the two columns on the other movable disk can be moved to a new column. I.e. the movement of the disk to an empty non-empty column column when two columns are not empty, a large movement of the disc. This step does not specify which disk to move, you may have thought there would be a variety of possibilities, it is not true, action can be implemented is unique.
⑶ repeated ⑴⑵ operation, will be able to finally complete the move by the provisions of the Tower of Hanoi.
So the result is very simple, is moved in one direction in accordance with sequin move rule:
The mobile third-order Tower of Hanoi: A → C, A → B , C → B, A → C, B → A, B → C, A → C

#include <iostream>
#include <string.h>
#include <stdio.h>
#define maxnum 50
using namespace std;

int hanoi(int n, char a, char b, char c)
{
    int num1,num2;
    if(n == 1)
    {
        cout<<a<<'-->'<<c;
        return 1;
    }
    else
    {
        num1 = hanoi(n-1, a, c, b);//将n-1个盘子从a移动到b
        cout<<a<<'-->'<<c;//将最下面的盘子从a移动到c
        num2 = hanoi(n-1, b, a, c);//将n-1个盘子从b移动到c
        return num1 + num2 + 1;
    }
}
int main()
{
    int n;
    cout<<"请输入汉诺塔盘子的个数:";
    cin>>n>>endl;
    cout<<hanoi(n,'A','B','C');
    return 0;
}

Blog continuously updated, there are any mistakes or questions, please leave a message, will reply the next day, thank you

Published 11 original articles · won praise 0 · Views 117

Guess you like

Origin blog.csdn.net/qq_44651133/article/details/103989059