Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <windows.h>
- using namespace std;
- int n;
- vector<int> A, B, C;
- void Initiate()
- {
- cin >> n;
- for( int i=n ; i>=1 ; i-- )
- A.push_back(i);
- system("cls");
- }
- void Show()
- {
- system("cls");
- cout << endl << "A: ";
- for( int i=0 ; i<A.size() ; i++ )
- cout << A[i] << " ";
- cout << endl << "B: ";
- for( int i=0 ; i<B.size() ; i++ )
- cout << B[i] << " ";
- cout << endl << "C: ";
- for( int i=0 ; i<C.size() ; i++ )
- cout << C[i] << " ";
- cout << endl;
- }
- void Move( int disk )
- {
- int location = 1;
- for( int i=1 ; i<=3 ; i++ )
- {
- if( i == 1 && A[A.size()-1] == disk )
- {
- location = 1;
- break;
- }
- else if( i == 2 && B[B.size()-1] == disk )
- {
- location = 2;
- break;
- }
- else if( i == 3 && C[C.size()-1] == disk )
- {
- location = 3;
- break;
- }
- }
- int nextLocation = location;
- for( int i=1 ; i<=2 ; i++ )
- {
- nextLocation ++;
- if( nextLocation > 3 )
- nextLocation = nextLocation%3;
- if( nextLocation == 1 )
- if( A.empty() )
- i=3;
- else if( A[A.size()-1] > disk )
- i=3;
- if( nextLocation == 2 )
- if( B.empty() )
- i=3;
- else if( B[B.size()-1] > disk )
- i=3;
- if( nextLocation == 3 )
- if( C.empty() )
- i=3;
- else if( C[C.size()-1] > disk )
- i=3;
- }
- if( location == 1 )
- A.pop_back();
- else if( location == 2 )
- B.pop_back();
- else if( location == 3 )
- C.pop_back();
- if( nextLocation == 1 )
- A.push_back(disk);
- else if( nextLocation == 2 )
- B.push_back(disk);
- else if( nextLocation == 3 )
- C.push_back(disk);
- }
- void SolveTOH_Recursively( int n_disks )
- {
- if( n_disks == 1 )
- {
- Move(1);
- Show();
- Sleep(500);
- }
- else
- {
- SolveTOH_Recursively( n_disks-1 );
- Move( n_disks );
- Show();
- Sleep(500);
- SolveTOH_Recursively( n_disks-1 );
- }
- }
- int main()
- {
- Initiate();
- Show();
- Sleep(500);
- SolveTOH_Recursively(n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment