The recursive problem of C++,hanoi Tower has always been a classic problem, and we often use it when we learn the data structure.
Because of its time complexity and space complexity are very high, we do not recommend the use of this algorithm in practical applications, moving n plates,
Requires 2 of the N power minus one step, for example: 5 plates, 31 steps, 10 plates, 1023 steps.
Below, I tidied up about the C + + recursive code implementation process, I hope that everyone's learning is helpful.
- #include <iostream>
- using namespace Std;
- The first tower for the initial tower, the middle tower for borrowing the tower, the last one tower for the goal tower
- int step=1; //record number of steps
- void Move (int n,char from,char to) //The plate numbered n is moved from
- {
- cout<< "<<step++<<" Step: "<<n<<" Plate <<from<< "--------" <<to< <endl;
- }
- void Hanoi (int N,char from,Char denpend_on,char to)//n plates moved from the initial tower to the target tower (using borrowed towers)
- {
- if (n==1)
- Move (1,from,to); //Only one dish is to move the plate on the first tower to the destination directly
- Else
- {
- Hanoi (N-1,FROM,TO,DENPEND_ON); The first n-1 plate of the initial tower is moved to the borrowed tower with the help of the destination tower.
- Move (N,from,to); //Move the remaining plate to the destination tower
- Hanoi (N-1,denpend_on,from,to); //Finally, the n-1 plates on the tower will be borrowed and moved to the destination tower .
- }
- }
- int main ()
- {
- cout<<"Please enter the number of plates:" <<endl;
- int n;
- scanf ("%d", &n);
- char x=' A ', y=' B ', z=' C ';
- cout<<"Plate movement process is as follows:" <<endl;
- Hanoi (N,X,Y,Z);
- return 0;
- }
Recursion about C + + (take Hanoi as an example)