forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTowerOfHanoi.java
More file actions
39 lines (33 loc) · 961 Bytes
/
TowerOfHanoi.java
File metadata and controls
39 lines (33 loc) · 961 Bytes
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
package com.thealgorithms.recursion;
/**
* Tower of Hanoi problem solved using recursion.
*
* <p>Time Complexity: O(2^n)</p>
* <p>Space Complexity: O(n)</p>
*/
public final class TowerOfHanoi {
private TowerOfHanoi() {
// Utility class
}
/**
* Solves the Tower of Hanoi problem.
*
* @param n number of disks
* @param source source rod
* @param helper auxiliary rod
* @param destination destination rod
*/
public static void towerOfHanoi(int n, char source, char helper, char destination) {
if (n == 1) {
System.out.println(
"Move disk 1 from " + source + " to " + destination
);
return;
}
towerOfHanoi(n - 1, source, destination, helper);
System.out.println(
"Move disk " + n + " from " + source + " to " + destination
);
towerOfHanoi(n - 1, helper, source, destination);
}
}