Recursion about C + + (take Hanoi as an example)

Source: Internet
Author: User

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.

  1. #include <iostream>
  2. using namespace Std;
  3. The first tower for the initial tower, the middle tower for borrowing the tower, the last one tower for the goal tower
  4. int step=1; //record number of steps
  5. void Move (int n,char from,char to) //The plate numbered n is moved from
  6. {
  7. cout<< "<<step++<<" Step: "<<n<<" Plate <<from<< "--------" <<to< <endl;
  8. }
  9. 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)
  10. {
  11. if (n==1)
  12. Move (1,from,to); //Only one dish is to move the plate on the first tower to the destination directly
  13. Else
  14. {
  15. 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.
  16. Move (N,from,to); //Move the remaining plate to the destination tower
  17. Hanoi (N-1,denpend_on,from,to); //Finally, the n-1 plates on the tower will be borrowed and moved to the destination tower .
  18. }
  19. }
  20. int main ()
  21. {
  22. cout<<"Please enter the number of plates:" <<endl;
  23. int n;
  24. scanf ("%d", &n);
  25. char x=' A ', y=' B ', z=' C ';
  26. cout<<"Plate movement process is as follows:" <<endl;
  27. Hanoi (N,X,Y,Z);
  28. return 0;
  29. }

Recursion about C + + (take Hanoi as an example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.