Skip to content

Commit 8f086c0

Browse files
Merge pull request #116 from manmeet-22/patch-1
Tower of Hanoi using Recursion
2 parents 77ca932 + 1e99c48 commit 8f086c0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Misc/TowerOfHanoiUsingRecursion

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.manmeet;
2+
3+
import java.util.Scanner;
4+
5+
public class TowerOfHanoi
6+
{
7+
public static void shift(int n, String startPole, String intermediatePole, String endPole)
8+
{
9+
if (n == 0) // if n becomes zero the program returns thus ending the loop.
10+
{
11+
return;
12+
}
13+
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
14+
shift(n - 1, startPole, endPole, intermediatePole);
15+
System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
16+
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
17+
shift(n - 1, intermediatePole, startPole, endPole);
18+
}
19+
public static void main(String[] args)
20+
{
21+
System.out.print("Enter number of discs on Pole 1: ");
22+
Scanner scanner = new Scanner(System.in);
23+
int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
24+
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
25+
}
26+
}

0 commit comments

Comments
 (0)