The Tower of Hanoi 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 objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk is allowed to move at a time..
- Bigger disk cannot be placed on the top of smaller disk.
Approach:
- Recursively Move N-1 disk from source to Auxiliary peg.
- Move the last disk from source to destination.
- Recursively Move N-1 disk from Auxiliary to destination peg.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TOH { | |
public void Tower(int n, String src, String aux, String dest){ | |
if(n==1){ | |
System.out.println("Move disc "+ n + " from " + src + " to " + dest ); | |
} | |
else{ | |
//make recursive call to move n-1 disks to aux nail | |
Tower(n–1, src, dest, aux); | |
//move the nth disc from "A" to "B" | |
System.out.println("Move disc " + n + " from " + src + " to " + dest ); | |
//Move n-1 disc from aux mail to dest tail | |
Tower(n–1, aux, src, dest); | |
} | |
} | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
int n = 4; | |
TOH i = new TOH(); | |
//A, B, C -> A is source, B is destination and C is Auxiliary Nail | |
i.Tower(n,"A","C","B"); | |
} | |
} |
Output:
Move disc 1 from A to C Move disc 2 from A to B Move disc 1 from C to B Move disc 3 from A to C Move disc 1 from B to A Move disc 2 from B to C Move disc 1 from A to C Move disc 4 from A to B Move disc 1 from C to B Move disc 2 from C to A Move disc 1 from B to A Move disc 3 from C to B Move disc 1 from A to C Move disc 2 from A to B Move disc 1 from C to B
As a complement to your post, I think you will be interested in this: https://thewalnut.io/visualizer/visualize/1322/342/ Instead of using recursion, the solution is based on a really simple, iterative, program (available in the same site) that’s guaranteed to solve Towers of Hanoi in the minimum number of steps.