Facebook
From Fg, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 180
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void printRod(vector<int>& rod) {
  7.     for (int disk : rod) {
  8.         cout << disk << " ";
  9.     }
  10.     cout << endl;
  11. }
  12.  
  13. void moveDisks(int n, vector<int>& source, vector<int>& target, vector<int>& auxiliary, char s, char t, char a) {
  14.     if (n > 0) {
  15.         moveDisks(n - 1, source, auxiliary, target, s, a, t);
  16.         target.push_back(source.back());
  17.         source.pop_back();
  18.  
  19.         cout << "Move disk " << n << " from " << s << " to " << t << endl;
  20.         cout << "A: "; printRod(source);
  21.         cout << "B: "; printRod(auxiliary);
  22.         cout << "C: "; printRod(target);
  23.         cout << endl;
  24.  
  25.         moveDisks(n - 1, auxiliary, target, source, a, t, s);
  26.     }
  27. }
  28.  
  29. int main() {
  30.     int n;  // Number of disks
  31.     cout << "Enter the number of disks: ";
  32.     cin >> n;
  33.  
  34.     vector<int> A, B, C;
  35.     // Initialize the source rod with disks 1 to n, where 1 is the smallest disk
  36.     for (int i = n; i > 0; i--) {
  37.         A.push_back(i);
  38.     }
  39.  
  40.     cout << "Initial state:\n";
  41.     cout << "A: "; printRod(A);
  42.     cout << "B: "; printRod(B);
  43.     cout << "C: "; printRod(C