![]() |
VOOZH | about |
The Tower of Hanoi is a classic mathematical puzzle involving three rods (A, B, and C) and n disks of different sizes. Initially, all disks are stacked on rod A in decreasing order of diameter - the largest disk at the bottom and the smallest at the top.
Goal is to move the entire stack to another rod (rod C) while following these rules:
Input: n = 3
Output:
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 CInput: n = 4
Output:
Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Disk 3 moved from A to B
Disk 1 moved from C to A
Disk 2 moved from C to B
Disk 1 moved from A to B
Disk 4 moved from A to C
Disk 1 moved from B to C
Disk 2 moved from B to A
Disk 1 moved from C to A
Disk 3 moved from B to C
Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Illustrations:
The idea is to use the helper node to reach the destination using recursion. Below is the pattern for this problem:
- Shift 'n-1' disks from 'A' to 'B', using C.
- Shift last disk from 'A' to 'C'.
- Shift 'n-1' disks from 'B' to 'C', using A.
Follow the steps below to solve the problem:
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
Time complexity: O(2n), There are two possibilities for every disk. Therefore, 2 * 2 * 2 * . . . * 2(n times) is 2n
Auxiliary Space: O(n), Function call stack space
Related Articles