1+ package com .thealgorithms .recursion ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+ import java .util .Scanner ;
6+
7+ /**
8+ * TowerOfHanoi - Solves the classic Tower of Hanoi puzzle
9+ *
10+ * This algorithm uses recursion to move a stack of disks from a source rod to a
11+ * destination rod, following the rules:
12+ * 1. Only one disk can be moved at a time.
13+ * 2. Each move consists of taking the upper disk from one of the stacks and
14+ * placing it on top of another stack.
15+ * 3. No disk may be placed on top of a smaller disk.
16+ *
17+ * Example: If n = 3, Source = 'A', Destination = 'C', Auxiliary = 'B'
18+ * Resulting moves will guide disks from A to C using B.
19+ *
20+ * @author justanothercoder
21+ * @see <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Tower of Hanoi</a>
22+ */
23+ public final class TowerofHanoi {
24+
25+ private TowerofHanoi () {
26+
27+ // Utility class
28+ }
29+
30+ /**
31+ * Solves the Tower of Hanoi puzzle and returns the list of moves
32+ *
33+ * @param n number of disks
34+ * @param source the source rod
35+ * @param destination the destination rod
36+ * @param auxiliary the auxiliary rod
37+ * @return list of moves as strings
38+ */
39+ public static List <String > solveTowerOfHanoi (int n , char source , char destination , char auxiliary ) {
40+ List <String > moves = new ArrayList <>();
41+ if (n <0 ){
42+ throw new IllegalArgumentException ("Number of disks cannot be negative" );
43+ }
44+ moveDisks (n , source , destination , auxiliary , moves );
45+ return moves ;
46+ }
47+
48+ /**
49+ * Recursive helper method to move disks
50+ *
51+ * @param n number of disks
52+ * @param source the source rod
53+ * @param destination the destination rod
54+ * @param auxiliary the auxiliary rod
55+ * @param moves list to record the moves
56+ */
57+ private static void moveDisks (int n , char source , char destination , char auxiliary , List <String > moves ) {
58+ if (n == 1 ) {
59+ moves .add ("Move disk 1 from rod " + source + " to rod " + destination );
60+ return ;
61+ }
62+ moveDisks (n - 1 , source , auxiliary , destination , moves );
63+ moves .add ("Move disk " + n + " from rod " + source + " to rod " + destination );
64+ moveDisks (n - 1 , auxiliary , destination , source , moves );
65+ }
66+
67+ public static void main (String [] args ){
68+ Scanner scanner = new Scanner (System .in );
69+ System .out .print ("Enter the number of disks: " );
70+ int n = scanner .nextInt ();
71+ List <String > result = solveTowerOfHanoi (n , 'A' , 'C' , 'B' );
72+
73+ for (String move : result ){
74+ System .out .println (move );
75+ }
76+ }
0 commit comments