Java Program. The idea of the problem is: 1. There are three towers which can be
ID: 3691499 • Letter: J
Question
Java Program.
The idea of the problem is:
1. There are three towers which can be represented by source, temp and destination
2. We have a stack of n disks on the source tower; all the disks have a different diameter. The largest disk is at the bottom and the smallest is at the top.
3. The goal is to transfer all the disks, one at a time, to the destination tower using all three towers for help. No larger disk may ever be on top of a smaller disk.
The recursion solution to the problem for the general case (n-1):
1. Transfer the top(n-1) disks from the source tower to the temporary tower.
2. Transfer the one remaining disk (the largest) from the source to the destination
3. Transfer the (n-1) disks from the temporary to the destination
base case : n=0, no disks to transfer
Code the tower of hanoi problem. Your solution should output to the user which disks are being transferred and to which tower as the program is executing.
Explanation / Answer
TowerOfHanoiTest.java
/*
* Java Program to Solve Tower of Hanoi Problem using Stacks
*/
/* Class TowerOfHanoiTest */
public class TowerOfHanoiTest{
public static void main(String[] args) {
int nDisks = 3;
char source = 'A';
char temp = 'B';
char destination = 'C';
doTowers(nDisks, source, temp, destination);
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from " + from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
Output:
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.