In this Java tutorial, we are going to discuss the famous Tower of Hanoi problem using ‘n’ disks. We are going to solve it using recursive function calling approach.
Tower of Hanoi Problem using recursion in Java
The Tower of Hanoi is a Mathematical puzzle. It consists of three rods and ‘n’ disks of different sizes which can slide onto any rod. In the puzzle, there are three rods suppose, left one is source rod, middle one Auxiliary rod, and right one destination rod. Source rod consists of ‘n’ disks in descending order of their sizes considering from the bottom where the smallest disk is at the top. We have to move all disks from source rod to destination rod using auxiliary rod by following rules:-
- We can not move more than one disk at a time
- We are not allowed to place a larger disk on a smaller one
Tower of Hanoi problem in Java
class Codespeedy { static void result(long n, char source, char destination, char auxiliary) { if (n == 1) { System.out.println("Move disk 1 from " + source + " to " + destination); // print the task return; } result(n-1, source, auxiliary, destination); System.out.println("Move disk " + n + " from " + source + " to " + destination); // print the task result(n-1, auxiliary, destination, source); } public static void main(String args[]) { long n = 3; // Number of disks result(n,'A','C','B'); // A, B and C are names of rods } }
Output:
Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C