Skip to content
This repository has been archived by the owner on Oct 5, 2021. It is now read-only.

Added : Code for Tower of Hanoi Problem in Java #669

Merged
merged 3 commits into from
Oct 5, 2021
Merged
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
30 changes: 30 additions & 0 deletions Java/Others/TowerOfHanoi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
public class TowerOfHanoi {
public static void towerOfHanoiPrint(int n, char source, char destination, char helper) {
if (n == 1) {
System.out.println("Move the 1st disk from " + source + " to Destination " + destination);
return;
}
towerOfHanoiPrint(n - 1, source, helper, destination);
System.out.println("Move the " + n + "th disk from " + source + " to Destination " + destination);
towerOfHanoiPrint(n - 1, helper, destination, source);
}

public static long toh(int N, char from, char to, char aux) {
long count = 0;
if (N > 0) {
count = toh(N - 1, from, aux, to);
// System.out.println("move disk " + N + " from rod " + from + " to rod " + to);
count++;
count += toh(N - 1, aux, to, from);
}
return count;
}

public static void main(String args[]) {
System.out.print("Steps required : \n");
towerOfHanoiPrint(3, 'A', 'C', 'B');

System.out.print("Count of Steps : ");
System.out.println(toh(3, 'A', 'C', 'B'));
}
}