-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathTowerOfHanoi.java
More file actions
64 lines (59 loc) · 2.18 KB
/
TowerOfHanoi.java
File metadata and controls
64 lines (59 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.thealgorithms.recursion;
import java.util.ArrayList;
import java.util.List;
/**
* TowerOfHanoi - Solves the classic Tower of Hanoi puzzle
*
* This algorithm uses recursion to move a stack of disks from a source rod to a
* destination rod, following the rules:
* 1. Only one disk can be moved at a time.
* 2. Each move consists of taking the upper disk from one of the stacks and
* placing it on top of another stack.
* 3. No disk may be placed on top of a smaller disk.
*
* Example: If n = 3, Source = 'A', Destination = 'C', Auxiliary = 'B'
* Resulting moves will guide disks from A to C using B.
*
* @author justanothercoder-hub
* @see <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Tower of Hanoi</a>
*/
public final class TowerOfHanoi {
private TowerOfHanoi() {
// Utility class
}
/**
* Solves the Tower of Hanoi puzzle and returns the list of moves
*
* @param n number of disks
* @param source the source rod
* @param destination the destination rod
* @param auxiliary the auxiliary rod
* @return list of moves as strings
*/
public static List<String> solveTowerOfHanoi(int n, char source, char destination, char auxiliary) {
List<String> moves = new ArrayList<>();
if (n < 0) {
throw new IllegalArgumentException("Number of disks cannot be negative");
}
moveDisks(n, source, destination, auxiliary, moves);
return moves;
}
/**
* Recursive helper method to move disks
*
* @param n number of disks
* @param source the source rod
* @param destination the destination rod
* @param auxiliary the auxiliary rod
* @param moves list to record the moves
*/
private static void moveDisks(int n, char source, char destination, char auxiliary, List<String> moves) {
if (n == 1) {
moves.add("Move disk 1 from rod " + source + " to rod " + destination);
return;
}
moveDisks(n - 1, source, auxiliary, destination, moves);
moves.add("Move disk " + n + " from rod " + source + " to rod " + destination);
moveDisks(n - 1, auxiliary, destination, source, moves);
}
}