Skip to content
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

Create TowerOfHanoi #685

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions TowerOfHanoi
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Tower of Hanoi Problem in java
import java.util.Scanner;

public class TowerOfHanoiClass {
public static void main(String[] args) {
int n;

// Getting input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of disks:");
n = sc.nextInt();
towerOfHanoi(n, 'A', 'B', 'C');
}
public static void towerOfHanoi(int topN, char source, char auxiliary, char destination) {
if (topN == 1) {
System.out.println("Disk 1 from " + source + " to " + destination);
} else {
towerOfHanoi(topN - 1, source, destination, auxiliary);
System.out.println("Disk " + topN + " from " + source + " to " + destination);
towerOfHanoi(topN - 1, auxiliary, source, destination);
}
}
}