c ++ knowledge Tower of Hanoi summary 1

The long-troubled, difficult to overcome in the coming summary Tower of Hanoi

Part One What Tower of Hanoi in the end is it?

Tower of Hanoi (Tower of Hanoi) from Indian legend, the three magic stone pillars made large Brahma created the world, wherein a column bottom from the stack 64 upwardly gold disk. Brahma Brahman command to the disk in order of size from the bottom again placed on the other pillars. And predetermined, the disc can not be enlarged in a small disk, a disk can only be moved between the three pillars. - quote Wikipedia

That the disc from a column to another column, midway need to assist the completion of a post, and must be followed in this process , "the next big small" principle.

Part Two common problem: the printing step to move Tower of Hanoi


So this type of question should be how to do it?

 



Next Detailed Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
int n,flag;
void move(int x,char A,char B,char C){//x就是代表这是从下往上数(从大往小)第x个圆盘
    if(x==0)
        return;
//接下来开始想象你的面前有ABC,3个圆柱 其中第一个圆柱上放着x个圆盘,你想要把他们从第一个圆柱挪到第三个圆柱上 move(x
-1,A,C,B);//递归,这一句的意思相当于就是把当前圆盘上面的 x-1 这么一堆较小的圆盘 ,把他们从A挪到B(借助C柱) printf("%c->%c\n",A,C);//然后把它从A挪到C move(x-1,B,A,C);//现在A柱就空出来了,再把原来B上面x-1个圆盘挪到C(借助A)
//那么这样子,x个圆盘就都挪到C啦@@@
//有的时候看着这一堆ABC会发蒙
//别慌,把每一次“集体大挪动”都看成是从A挪到C,和第一次x=n是=时的初衷一样;只需要在递归的过程中把ABC分别代表的柱子的字母记录下来,在递归过程中打印即可
}
int main() { cin>>n; move(n,'A','B','C'); return 0; }

哈哈,其实它也不难!

 

 

Guess you like

Origin www.cnblogs.com/Tidoblogs/p/11105040.html