Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- void moveDisk(int disk, char source, char destination)
- {
- cout << "Move disk " << disk << " from " << source << " to " << destination << endl;
- }
- void towerOfHanoi(int n, char source, char auxiliary, char destination)
- {
- if(n == 1)
- {
- moveDisk(1, source, destination);
- return;
- }
- towerOfHanoi(n - 1, source, destination, auxiliary);
- moveDisk(n, source, destination);
- towerOfHanoi(n - 1, auxiliary, source, destination);
- }
- int main()
- {
- int n;
- cout << "Enter the number of disks: ";
- cin >> n;
- towerOfHanoi(n, 'A', 'B', 'C');
- return 0;
- }
- /*
- #include<iostream>
- using namespace std;
- /// Function to move a single disk from source to destination
- void moveDisk(int disk, char source, char destination)
- {
- cout << "Move disk " << disk << " from " << source << " to " << destination << endl;
- }
- /// Function to solve Tower of Hanoi with 'n' disks
- void towerOfHanoi(int n, char source, char auxiliary, char destination)
- {
- if(n == 1)
- {
- moveDisk(1, source, destination);
- return;
- }
- /// Move the top 'n-1' disks from source to auxiliary peg using destination peg as auxiliary
- towerOfHanoi(n - 1, source, destination, auxiliary);
- /// Move the largest disk from source to destination
- moveDisk(n, source, destination);
- /// Move the 'n-1' disks from auxiliary to destination peg using source peg as auxiliary
- towerOfHanoi(n - 1, auxiliary, source, destination);
- }
- int main()
- {
- int n;
- cout << "Enter the number of disks: ";
- cin >> n;
- towerOfHanoi(n, 'A', 'B', 'C'); /// A, B, and C are the names of the pillar
- return 0;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement