In: Computer Science
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there can be any amount of disks and there are either 3,4, or 5 pegs to store the disks(# of pegs and disks is manually inputted by user), in Tower of Hanoi game, the object of the game is move all the pieces from the 1st peg to the right most peg or the opposite side. You can place disks on top of each other only if disk under is a bigger number. Game ends when all pegs have been moved from left side to right side.
output example:
Disk 1 Moved from peg A to C
Disk 2 Moved from peg A to B
Disk 1 Moved from peg C to B
Disk 3 Moved from peg A to C
Disk 1 Moved from peg B to A
Disk 2 Moved from peg B to C
Disk 1 Moved from peg A to C
Here is the solution with recursion. Followed by outputs. Please do upvote thank you.
import java.util.*;
class Main
{
static void towerOfHanoi(int n, char from_peg, char to_peg, char
aux_rod)
{
if (n == 1)
{
System.out.println("Disk 1 moved from peg " + from_peg + " to " +
to_peg);
return;
}
towerOfHanoi(n-1, from_peg, aux_rod, to_peg);
System.out.println("Disk " + n + " moved from rod " + from_peg + "
to " + to_peg);
towerOfHanoi(n-1, aux_rod, to_peg, from_peg);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n = sc.nextInt(); // Number of pegs
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of
pegs
}
}