Posted on by Kalkicode
Code Divide And Conquer

# Tower of hanoi solution

The Tower of Hanoi is a classic problem in the field of computer science and mathematics. It involves a set of disks of different sizes placed on a rod, with the smallest disk at the top and the largest disk at the bottom. The challenge is to move all the disks from one rod to another, following a specific set of rules, using an auxiliary rod as temporary storage.

## Problem Statement and Description

Imagine three rods labeled A, B, and C. Initially, all the disks are stacked in decreasing order of size on rod A. The task is to move the entire stack of disks to rod C, obeying the following rules:

1. Only one disk can be moved at a time.
2. A larger disk cannot be placed on top of a smaller disk.
3. Disks can only be moved directly between the rods, and they must be placed on top of the stack on the destination rod.

## Example

Let's consider a Tower of Hanoi problem with 3 disks (labeled D1, D2, D3) and 3 rods (A, B, C). The initial configuration is:

• Rod A: D3, D2, D1
• Rod B: Empty
• Rod C: Empty

The goal is to move all the disks to rod C using rod B as the auxiliary rod.

## Idea to Solve the Problem

A recursive approach is used to solve the Tower of Hanoi problem efficiently. The following steps outline the approach:

1. If there's only one disk, move it directly from the source rod to the destination rod.
2. Otherwise, follow these steps recursively: a. Move the top (n-1) disks from the source rod to the auxiliary rod, using the destination rod as temporary storage. b. Move the nth disk from the source rod to the destination rod. c. Move the (n-1) disks from the auxiliary rod to the destination rod, using the source rod as temporary storage.

## Pseudocode

``````function towerOfHanoi(disk, source, destination, auxiliary)
if disk <= 0
return
towerOfHanoi(disk - 1, source, auxiliary, destination)
print "Move disk [disk] from tower [source] to [destination]"
towerOfHanoi(disk - 1, auxiliary, destination, source)``````

## Algorithm Explanation

The recursive algorithm for the Tower of Hanoi problem is divided into three steps:

1. Recursively move (disk-1) disks from the source rod to the auxiliary rod using the destination rod as temporary storage.
2. Move the nth disk from the source rod to the destination rod.
3. Recursively move the (disk-1) disks from the auxiliary rod to the destination rod using the source rod as temporary storage.

## Time Complexity

The time complexity of the Tower of Hanoi algorithm is O(2^n), where n is the number of disks. This is because, in each step, the algorithm solves two subproblems of size (n-1), leading to an exponential time complexity.

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post