Hanoi, classic recursion.
The classic Hanoi game believes that many students will play, the rules do not have to repeat, the encyclopedia is OK. There are three pillars a,b,c,a pillars with n sizes of plates, any two plates, the upper plate must be smaller than the plate below. Now, please write your program to calculate how to move the n plates to the C pillar, move only one plate at a time, move through the B pillars, any state, the plates of each pillar must be placed on a large plate on a small plate. Now enter two positive integer n, indicating that there are n plates, please output his every move.
#include <iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<cmath>using namespaceStd;inlineintRead () {intx=0, f=1;CharCh=GetChar (); for(;! IsDigit (CH); Ch=getchar ())if(ch=='-') f=-1; for(; isdigit (ch); Ch=getchar ()) x=x*Ten+ch-'0'; returnx*F;}intN,step;voidHanoiintNowChar from,CharUseCharTo ) { if(!now)return;//If you don't have a plate, you don't have to move.step++;//number of steps addedprintf"step%d:from%c to%c\n", step, from, to);//Output NowHanoi (now-1, from, To,use);//first move all the plates on the moving pillars to the pillars .Hanoi (now-1, use, from, to);//and then move all the plates on the pillar to the final pillar . return ;}intMain () {n=read (); Hanoi (N,'A','B','C');//move from A with B to C}
"Algorithm: 2" Hanoi Twin Towers