Solving Tower of Hanoi Problem
The Tower of Hanoi, a classic mathematical puzzle, challenges the mind with its simple rules yet complex solutions. Originating from an ancient legend, this brainteaser involves moving a stack of discs between three pegs, adhering to specific constraints. Beyond its recreational appeal, the puzzle has profound implications in computer science, particularly in the realm of algorithms and recursion.
The Tower of Hanoi problem is a classic mathematical puzzle, invented by the French mathematician Édouard Lucas in 1883. There are 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 disk is at the top, thus making a conical or a pyramid shape.
Objective:
Move all the disks from the starting rod (A) to the destination Rod (C) using a intermediate rod (B).
Source: Codespeedy
Best-suited Python courses for you
Learn Python with these high-rated online courses
Initial Setup:
- Rods: There are three rods – A, B, and C.
- Disks: A set of disks, each of different sizes. Initially, these disks are stacked on Rod A in descending order with the largest disk at the bottom and the smallest at the top.
Constraints | Rules:
- Single Move: Pick and move only one disk at a time.
- Top Disk: You can only move the top disk from any of the three rods.
- Placement: A disk can only be placed on top of another disk if it is smaller than the disk already on the rod. Alternatively, you can place the disk on an empty rod.
- Goal: The objective is to move the entire stack of disks from Rod A to Rod C, maintaining their size order.
Task:
Devise a strategy to move the entire stack of disks from Rod A to Rod C, while always adhering to the above constraints.
End State:
All n disks are stacked on Rod C in descending order of size, with the largest disk at the bottom and the smallest at the top.
Steps to Solve:
To move a stack of n disks from Rod A to Rod C using Rod B:
- Move Smaller Stack: Start by moving the top n-1 disks from Rod A to Rod B, using Rod C as a helper.
- Move Largest Disk: Then, move the largest disk (the bottom one) from Rod A directly to Rod C.
- Transfer Smaller Stack: Finally, move the n-1 disks that you placed on Rod B to Rod C, using Rod A as a helper.
This process is recursive until all disks are on Rod C. For moving the n-1 disks, you’ll again follow the same three steps, treating them as a new set of disks.
Example with 3 Disks:
- Move Two Disks to Rod B:
- Move Disk 1 (smallest) from Rod A to Rod C.
- Pick Disk 2 from Rod A to Rod B.
- Transfer Disk 1 from Rod C to Rod B, placing it on top of Disk 2.
- Move Largest Disk to Rod C:
- Move Disk 3 (largest) from Rod A to Rod C.
- Transfer Two Disks from Rod B to Rod C:
- Move Disk 1 from Rod B to Rod A.
- Move Disk 2 from Rod B to Rod C.
- Transfer Disk 1 from Rod A to Rod C, placing it on top of Disk 2.
Now, all the disks are on Rod C in the correct order!
Implementation of Tower of Hanoi in Python
In this section lets see how to solve the Tower of Hanoi problem using Python:
def tower_of_hanoi(n, source, auxiliary, target):
""" Parameters: - n: Number of disks. - source: The source rod. - auxiliary: The auxiliary rod. - target: The target rod. """
if n == 1: # Base case: If only one disk, move it directly from source to target. print(f"Move disk 1 from {source} to {target}") return
# Move n-1 disks from source to auxiliary rod using target as auxiliary. tower_of_hanoi(n-1, source, target, auxiliary)
# Move the nth disk from source to target. print(f"Move disk {n} from {source} to {target}")
# Move the n-1 disks from auxiliary rod to target using source as auxiliary. tower_of_hanoi(n-1, auxiliary, source, target)
# Example usage:# Get the number of disks from the user.n = int(input("Enter the number of disks: "))# Start the Tower of Hanoi solution with rods labeled 'A', 'B', and 'C'.tower_of_hanoi(n, 'A', 'B', 'C')
Time Complexity of Tower of Hanoi
The time complexity of the Tower of Hanoi problem is O(2n−1), which is exponential. This is because for n disks, the number of moves required is 2n−1.
Here’s a brief explanation:
- To move n disks from the source rod to the target rod using an auxiliary rod, you first need to move n−1 disks from the source rod to the auxiliary rod. This requires 2n−1 -1 moves.
- Then, you move the nth disk (the largest one) from the source rod to the target rod. This requires 1 move.
- Finally, you move the n−1 disks from the auxiliary rod to the target rod. Again, this requires 2n−1 – 1 moves.
When you sum up these moves, you get: 2n−1−1+1+2n−1−1=2n−1
So, the time complexity of the Tower of Hanoi problem is O(2n).
Implementation of Tower of Hanoi in C++
In this section lets see how to solve the Tower of Hanoi problem using C++:
#include <iostream>using namespace std;
/** * Recursive function to solve the Tower of Hanoi problem. * * @param n Number of disks. * @param source The source rod. * @param auxiliary The auxiliary rod. * @param target The target rod. */
void tower_of_hanoi(int n, char source, char auxiliary, char target) { if (n == 1) { // Base case: If only one disk, move it directly from source to target. cout << "Move disk 1 from " << source << " to " << target << endl; return; }
// Move n-1 disks from source to auxiliary rod using target as auxiliary. tower_of_hanoi(n-1, source, target, auxiliary);
// Move the nth disk from source to target. cout << "Move disk " << n << " from " << source << " to " << target << endl;
// Move the n-1 disks from auxiliary rod to target using source as auxiliary. tower_of_hanoi(n-1, auxiliary, source, target);}
int main() { int n; // Get the number of disks from the user. cout << "Enter the number of disks: "; cin >> n;
// Start the Tower of Hanoi solution with rods labeled 'A', 'B', and 'C'. tower_of_hanoi(n, 'A', 'B', 'C'); return 0;}
Mathematical Significance: The Tower of Hanoi is frequently used in psychology research as a task to measure problem-solving skills. It also has interesting mathematical properties. The minimum number of moves required to solve the Tower of Hanoi puzzle is 2n – 1, where n is the number of disks.
Fun Fact: If you have 3 rings, you can move them all in just 7 steps following the rules. The more rings you have, the more steps it takes. For example, with 4 rings, it takes 15 steps!
Application of Tower of Hanoi
Application Area | How Tower of Hanoi Principles Are Applied |
---|---|
Computer Data Storage | The sequence of moves in the Tower of Hanoi is used to determine the optimal rotation schedule for backup tapes, ensuring that older backups are overwritten in a systematic manner. |
Robotics | Robots handling stacked objects use the Tower of Hanoi’s rules to determine the optimal sequence of moves, ensuring no larger object is placed on a smaller one. |
Computer Algorithms | The Tower of Hanoi is directly implemented to teach recursion, demonstrating how a complex problem can be broken down into simpler, repetitive tasks. |
Manufacturing | In assembly lines where components need to be stacked or arranged in a specific order, the Tower of Hanoi’s principle of moving items without placing a larger one on a smaller one can guide the sequence of operations to avoid mistakes and rework. |
Telecommunications | In hierarchical network designs, the Tower of Hanoi’s recursive approach can be used as a model to optimize the sequence of connecting nodes or switches, ensuring that higher-capacity nodes (analogous to larger disks) handle more traffic and lower-capacity nodes (smaller disks) handle less. |
Logistics | In warehousing, when items are stored in bins or racks, the Tower of Hanoi principle can guide the arrangement such that items are easily accessible. For instance, frequently accessed items (analogous to smaller disks) can be placed in more accessible locations, while less frequently accessed items (larger disks) can be placed deeper or higher up. |
Legend of Tower of Hanoi:
There’s a popular legend associated with this puzzle. According to the legend there’s a temple in Varanasi containing a large room with three time-worn posts in it. It is surrounded by 64 golden disks. Following the command of ancient prophecy, Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks in accordance with the immutable rules of the Brahma puzzle since the beginning of time. The puzzle gets complete when the priests finish their work, and the legend says that the world will end at that moment.
It is not clear whether Lucas invented this legend or was inspired by it.
But if the legend was true, solving the puzzle for 64 disks would require 264 -1 moves, which is 18,446,744,073,709,551,615 moves. Even if one move was made every second, it would take more than 580 billion years to complete! This gives an idea of the exponential growth associated with the puzzle’s solution.
Many versions of the legend exist. Some show the temple as a monastery and the priests as monks. People mention different places for the temple, like Hanoi, Vietnam. Different religions connect to the story. Some stories say the tower was made at the start of the world. Others say the priests or monks can only move one piece a day.
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio