Explore the Tower of Hanoi problem

Explore the Tower of Hanoi problem

The original title

There are three pillars, each pillar start out empty. We put three columns numbered 1, 2, 3, and now, there is the first pillar N A plate arranged in small to large sizes, our aim is to sequentially transfer these plates from the first column to the third root. Is required, i.e. in order one on top of each column on the plate, of the sum of the size of the plate is smaller than that during the move. So how can we move?

Link to submit evaluation area (codevs)

Thinking

Let's think such a thought is that we define a function K A N S U ( X , Y, with) , Of this function is to x The pillars Y A moving plate according to the order from The post. In the process of thinking, you must not consider how to move, just know that we want to move just fine. In this way, call again K A N S U ( A , N1,B) ,right now B A pillar in turn have folded N1 A plate, and A The largest on the left of that one, C On not one. Now we analyze, A Only one of the largest, that can A Any dish placed. So, the A The rest to the largest mobile C On, so C That is the biggest on the up. right now, A It is empty, B There N1 A, C On one of the greatest.

Here we have your attention, at the beginning A There are a pillar N A plate, B Pillars and C No plate on the pillar, and now A On no, B on N1 A, C On one of the biggest. because C On one of the greatest, so you can put any of the above plate, it is equivalent to empty. In this way, we'll move we have to solve N A plate of simplifying the issue has become mobile N1 Matter of dishes (just a different location), which is the use of the idea of ​​recursion.

Now we have completed one of the biggest moved to C On the task, then our ultimate mission to understand, is the largest of each moved C Pillar, so the biggest piled up, the plot to N We get a result.

Fake code

S1:利用Kansu(A, N - 1, B)将A上的N - 1个盘子按照顺序移动到B柱子上
S2:利用Move(A, C)将A柱子上剩下的一个最大的盘子移动到C柱子上
S3:利用Kansu(B, N - 2, A)将B上的N - 2个盘子按照顺序移动到B柱子上
......
最后在一个一个Move的过程中,C上就按照从大到小的顺序垒好了N个盘子。

C ++ code

#include <cmath>
#include <iostream>

void Hanoi(const int n, const int A, const int B, const int C)
{

    if (n > 0)
    {
        Hanoi(n - 1, A, C, B);
        std::cout << n << " from " << char (64 + t.x)  << " to " << char (64 + t.y) << '\n';
        Hanoi(n - 1, C, A, B);
    }
}


int main(int argc, char ** argv)
{
    int n;
    std::cin >> n;
    std::cout << std::pow(2, n) - 1 << std::endl;
    // 2^n - 1 表示步数总数
    Hanoi(n, 1, 3, 2);
    return 0;
}
Published 40 original articles · won praise 0 · Views 5163

Guess you like

Origin blog.csdn.net/edward00324258/article/details/71214244