1#include <iostream>2 using namespacestd;3 //The first tower for the initial tower, the second tower for the relay tower, the third tower for the goal tower4 5 inti =1;//record number of steps6 voidMoveintNChar from,CharTo)//The plates numbered n are transferred from the tower to the to tower.7 {8cout<<"Section"<<i++<<"Step: Add"<<n<<"Number plate"<< from<<"---->"<<to<<endl;//Output Example: 1th step: >c Plate a----1th9 } Ten One voidHanoiintNChar from,CharDENPEND_ON,CharRoo//Hanoi recursive function, the parameters are plate number, starting tower, relay tower, Target tower A { - if(n==1) - { theMove1, from, to);//when the number of plates to be moved is 1, move the plate directly from the starting tower to the target tower - } - Else - { +Hanoi (n1, from, to,denpend_on);//when the number of plates that need to be moved is not 1, - //move the tray outside the bottom plate from the starter tower to the transfer tower with the target tower. +Move (N, from, to);//move the remaining last tower directly from the starting tower to the target tower. AHanoi (n1, denpend_on, from, to);//move the n-1 plates that were previously removed from the tower to the target tower with the starting tower at } - } - - intMain () - { - intn =0;//N is the number of plates incout<<"Please enter the number of plates:"; -Cin>>N; to while(n<=0)//Judging the number of illegal plates + { -cout<<"the number of plates should not be less than 1, please re-enter:"; theCin>>N; * } $ if(n>0)Panax Notoginseng { - Charx='A', y='B', z='C'; thecout<<"The plate movement is as follows:"<<Endl; +Hanoi (N,X,Y,Z);//Call the Hanoi function A return 0; the } +}
Operation Result:
Recursive implementation, the process is not stored.
The storage of the tray position is not used with the stack, showing only the results.
Understand recursion as the main bar, like stuffed buns stuffed bun (the limit is steamed bread).
Invasion and deletion.
Original C code Source: http://blog.csdn.net/kkkkkxiaofei/article/details/8333644/
C + + code implementation of Hanoi tower problem (Hanoi)