Skip to content

Create Tower_of_Hanoi.cpp #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions games-based-on-dsa/Tower_of_Hanoi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//Tower of hanoi
#include <iostream>
using namespace std;

// Function to solve Tower of Hanoi
void towerOfHanoi(int n, char source, char target, char auxiliary) {
// Base case: only one disk to move
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << target << endl;
return;
}
// Move n-1 disks from source to auxiliary, using target as auxiliary
towerOfHanoi(n - 1, source, auxiliary, target);
// Move the nth disk from source to target
cout << "Move disk " << n << " from " << source << " to " << target << endl;
// Move the n-1 disks from auxiliary to target, using source as auxiliary
towerOfHanoi(n - 1, auxiliary, target, source);
}

int main() {
int n; // Number of disks
cout << "Enter the number of disks: ";
cin >> n;
// Solve the Tower of Hanoi problem
towerOfHanoi(n, 'A', 'C', 'B'); // A = source, C = target, B = auxiliary
return 0;
}