From cd9810a571ba309f6babd585028555f82188cbb6 Mon Sep 17 00:00:00 2001 From: Kunj Shukla Date: Sun, 8 Oct 2023 14:30:47 +0530 Subject: [PATCH] Tower of Hanoi in Java --- .../JAVA/Tower-of-Hanoi.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 GeeksForGeeks/Celebrity-Problem/JAVA/Tower-of-Hanoi.java diff --git a/GeeksForGeeks/Celebrity-Problem/JAVA/Tower-of-Hanoi.java b/GeeksForGeeks/Celebrity-Problem/JAVA/Tower-of-Hanoi.java new file mode 100644 index 0000000..7dc0281 --- /dev/null +++ b/GeeksForGeeks/Celebrity-Problem/JAVA/Tower-of-Hanoi.java @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class TowerOfHanoi { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter the number of disks: "); + int n = sc.nextInt(); + towerOfHanoi(n, 'A', 'C', 'B'); + sc.close(); + } + + public static void towerOfHanoi(int n, char fromRod, char toRod, char auxRod) { + if (n == 1) { + System.out.println("Move disk 1 from rod " + fromRod + " to rod " + toRod); + return; + } + towerOfHanoi(n - 1, fromRod, auxRod, toRod); + System.out.println("Move disk " + n + " from rod " + fromRod + " to rod " + toRod); + towerOfHanoi(n - 1, auxRod, toRod, fromRod); + } +}