Skip to content

Create TowerOfHanoi.java #5531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
25 changes: 25 additions & 0 deletions src/main/java/com/thealgorithms/Recursion/TowerOfHanoi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
public class TowerOfHanoi {

// Method to solve Tower of Hanoi
public static void solveTowerOfHanoi(int n, char source, char auxiliary, char target) {
// Base case: If there is only one disk, move it from source to target
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + target);
return;
}

// Move n-1 disks from source to auxiliary, using target as a temporary peg
solveTowerOfHanoi(n - 1, source, target, auxiliary);

// Move the nth disk from source to target
System.out.println("Move disk " + n + " from " + source + " to " + target);

// Move the n-1 disks from auxiliary to target, using source as a temporary peg
solveTowerOfHanoi(n - 1, auxiliary, source, target);
}

public static void main(String[] args) {
int numberOfDisks = 3; // You can change the number of disks here
solveTowerOfHanoi(numberOfDisks, 'A', 'B', 'C'); // A, B and C are names of rods
}
}
Loading