2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2017-10-01 02:47:23 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
class TowerOfHanoi {
|
|
|
|
public static void shift(int n, String startPole, String intermediatePole, String endPole) {
|
|
|
|
// if n becomes zero the program returns thus ending the loop.
|
|
|
|
if (n == 0) {
|
2017-10-01 02:47:23 +08:00
|
|
|
return;
|
|
|
|
}
|
2019-05-09 19:32:54 +08:00
|
|
|
|
|
|
|
|
2017-10-01 02:47:23 +08:00
|
|
|
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
|
|
|
|
shift(n - 1, startPole, endPole, intermediatePole);
|
2020-05-25 05:21:28 +08:00
|
|
|
System.out.println("%nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
|
2017-10-01 02:47:23 +08:00
|
|
|
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
|
|
|
|
shift(n - 1, intermediatePole, startPole, endPole);
|
|
|
|
}
|
2019-05-09 19:32:54 +08:00
|
|
|
|
|
|
|
public static void main(String[] args) {
|
2017-10-01 02:47:23 +08:00
|
|
|
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
|
2020-01-29 00:34:52 +08:00
|
|
|
scanner.close();
|
2017-10-01 02:47:23 +08:00
|
|
|
}
|
|
|
|
}
|