mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +08:00
Tower of Hanoi using Recursion
This commit is contained in:
26
Misc/TowerOfHanoiUsingRecursion
Normal file
26
Misc/TowerOfHanoiUsingRecursion
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package com.manmeet;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class TowerOfHanoi
|
||||||
|
{
|
||||||
|
public static void shift(int n, String startPole, String intermediatePole, String endPole)
|
||||||
|
{
|
||||||
|
if (n == 0) // if n becomes zero the program returns thus ending the loop.
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
|
||||||
|
shift(n - 1, startPole, endPole, intermediatePole);
|
||||||
|
System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
|
||||||
|
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
|
||||||
|
shift(n - 1, intermediatePole, startPole, endPole);
|
||||||
|
}
|
||||||
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
System.out.print("Enter number of discs on Pole 1: ");
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
|
||||||
|
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user