C + + implementation of hannotta examples

  • 2020-05-27 06:41:07
  • OfStack

C + + implementation of Hanover tower examples

Preface:

There are A, B, C3 tower, N plates (numbered 1-N from small to large) all in A tower at the beginning, now we need to move all N plates to C tower (according to the rules of Hanoi tower), find the minimum number of times of movement and the details of each movement.

Requirements:

We need to use both recursive method and elimination of tail recursion.

The disk number N is read in by the user from the standard input, represented as an integer, and then called by both methods to output the result on the screen as described in the following example (normally one input will display the same output twice).

Implementation code:


#include<iostream>
using namespace std;
void move(int count,char start='a',char finish='b',char temp='c')
{
 if(count>0)
 {
  move(count-1,start,temp,finish);
 cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
 move(count-1,temp,finish,start);
 }
}
void move_without_recursion(int count,char start='a',char finish='b',char temp='c')
{
 char swap;
 while(count>0)
 {
  move_without_recursion(count-1,start,temp,finish);
 cout<<"Move "<<count<<" from "<<start<<" to "<<finish<<endl;
 count--;
 swap=start;
 start=temp;
 temp=swap;
 }
}
int main()
{
 int count;
 cout<<"please enter the number:";
 cin>>count;
 cout<<" The recursive method runs the procedure :"<<endl;
  move(count);
  cout<<" Eliminate the tail recursive method run :"<<endl;
  move_without_recursion(count);
return 0;
}


If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: