Advertisement
YouKnowWho07

Tower of Hanoi

Sep 22nd, 2023 (edited)
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. void moveDisk(int disk, char source, char destination)
  5. {
  6.     cout << "Move disk " << disk << " from " << source << " to " << destination << endl;
  7. }
  8.  
  9. void towerOfHanoi(int n, char source, char auxiliary, char destination)
  10. {
  11.     if(n == 1)
  12.     {
  13.         moveDisk(1, source, destination);
  14.         return;
  15.     }
  16.     towerOfHanoi(n - 1, source, destination, auxiliary);
  17.     moveDisk(n, source, destination);
  18.     towerOfHanoi(n - 1, auxiliary, source, destination);
  19. }
  20.  
  21. int main()
  22. {
  23.     int n;
  24.     cout << "Enter the number of disks: ";
  25.     cin >> n;
  26.  
  27.     towerOfHanoi(n, 'A', 'B', 'C');
  28.     return 0;
  29. }
  30.  
  31. /*
  32.  
  33. #include<iostream>
  34. using namespace std;
  35.  
  36. /// Function to move a single disk from source to destination
  37. void moveDisk(int disk, char source, char destination)
  38. {
  39.     cout << "Move disk " << disk << " from " << source << " to " << destination << endl;
  40. }
  41.  
  42. /// Function to solve Tower of Hanoi with 'n' disks
  43. void towerOfHanoi(int n, char source, char auxiliary, char destination)
  44. {
  45.     if(n == 1)
  46.     {
  47.         moveDisk(1, source, destination);
  48.         return;
  49.     }
  50.     /// Move the top 'n-1' disks from source to auxiliary peg using destination peg as auxiliary
  51.     towerOfHanoi(n - 1, source, destination, auxiliary);
  52.     /// Move the largest disk from source to destination
  53.     moveDisk(n, source, destination);
  54.     /// Move the 'n-1' disks from auxiliary to destination peg using source peg as auxiliary
  55.     towerOfHanoi(n - 1, auxiliary, source, destination);
  56. }
  57.  
  58. int main()
  59. {
  60.     int n;
  61.     cout << "Enter the number of disks: ";
  62.     cin >> n;
  63.  
  64.     towerOfHanoi(n, 'A', 'B', 'C'); /// A, B, and C are the names of the pillar
  65.     return 0;
  66. }
  67.  
  68. */
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement