There are three pillars, each pillar start out empty. We put three columns numbered 1, 2, 3, and now, there is the first pillarNA 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?
Let's think such a thought is that we define a functionK A N S U ( X , Y, with), Of this function is toxThe pillarsYA moving plate according to the orderfromThe 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 againK A N S U ( A , N−1,B),right nowBA pillar in turn have foldedN−1A plate, andAThe largest on the left of that one,COn not one. Now we analyze,AOnly one of the largest, that canAAny dish placed. So, theAThe rest to the largest mobileCOn, soCThat is the biggest on the up. right now,AIt is empty,BThereN−1A,COn one of the greatest.
Here we have your attention, at the beginningAThere are a pillarNA plate,BPillars andCNo plate on the pillar, and nowAOn no,BonN−1A,COn one of the biggest. becauseCOn 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 solveNA plate of simplifying the issue has become mobileN−1Matter of dishes (just a different location), which is the use of the idea of recursion.
Now we have completed one of the biggest moved toCOn the task, then our ultimate mission to understand, is the largest of each movedCPillar, so the biggest piled up, the plot toNWe 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(constint n, constint A, constint B, constint 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);
return0;
}