Write a C++ Code For above Mr. Yu will share the details with you But it’s about Hanoi Tower
时间: 2024-10-22 08:19:27 浏览: 25
Hanoi Tower problem is a classic computer science puzzle that involves moving disks from one peg to another while following certain rules. The goal is to move all disks from the first peg to the third peg, obeying these constraints:
1. Only one disk can be moved at a time.
2. A larger disk cannot be placed on top of a smaller disk.
Here's a simple recursive algorithm in C++ for solving the Hanoi Tower problem:
```cpp
#include <iostream>
using namespace std;
void hanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n >= 1) {
// Move n - 1 disks from 'from_rod' to 'aux_rod'
hanoi(n - 1, from_rod, aux_rod, to_rod);
// Move the nth disk from 'from_rod' to 'to_rod'
cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl;
// Move the n - 1 disks from 'aux_rod' to 'to_rod', now including the nth disk
hanoi(n - 1, aux_rod, to_rod, from_rod);
}
}
int main() {
int num_disks; // Number of disks
cout << "Enter the number of disks: ";
cin >> num_disks;
// Call the function with initial parameters
hanoi(num_disks, 'A', 'C', 'B'); // Assuming 'A', 'B', and 'C' are pegs
return 0;
}
```
In this code, `hanoi` function takes three rods as arguments and recursively solves the tower by breaking down the problem into smaller sub-problems until it reaches the base case where there's no disk to move. When running this code, users can input the number of disks to start the tower, and the program prints out the steps needed to solve the puzzle.
阅读全文