Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/main/java/com/thealgorithms/recursion/TowerOfHanoi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
}
}
Loading