Question
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower) is a mathematical game or puzzle. It consists of three rods and
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack.
No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves.
Implement towerOfHanoi function that produces steps of moving disks from rod 'A' to rod 'C' using an auxiliary rod 'B'.
For example: assume tower 'A' consists of 3 disks (tower 'B' and 'C' are initially empty) and we want to move disks to tower 'C'. following instructions should be produced by towerOfHanoi function.
Disk 1 moved from A to C Disk 2 moved from A to B Disk 1 moved from C to B Disk 3 moved from A to C Disk 1 moved from B to A Disk 2 moved from B to C Disk 1 moved from A to C
/* 'n' is the number of disks. 'from', 'to' and 'aux' are towers. */ void towerOfHanoi(int n, char from, char to, char aux);
====================== main.cpp ===========================
#include
int main() { int n; // Number of disks cout << "Enter num of disks:" << endl; cin >> n; towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started