Question
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class TowersOfHanoiRecursive { static PrintWriter out; //define numOfDisks to start with and label rods int numDisks;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TowersOfHanoiRecursive {
static PrintWriter out; //define numOfDisks to start with and label rods
int numDisks;
char startingRod;
char moveRod;
char emptyRod;
static void TowersOfHanoiRecursive(int numDisks, char startingRod, char moveRod, char emptyRod) {
if (numDisks == 1) {
out.println("Move disk 1 from tower " + startingRod + " to tower " + moveRod);
return;
} else {
TowersOfHanoiRecursive(numDisks -1, startingRod, emptyRod, moveRod);
System.out.println("Move disk " + numDisks + "from rod" + startingRod + " to Tower" + emptyRod);
TowersOfHanoiRecursive(numDisks-1, emptyRod, startingRod, moveRod);
}
}
public static void main (String args[]) throws IOException {
int n;
out = new PrintWriter (new FileWriter("RecursiveTowers.txt"));
System.out.println("Enter number of disks");
Scanner input = new Scanner(System.in);
n=input.nextInt();
int numDisks = n;
long start = System.nanoTime();
TowersOfHanoiRecursive(numDisks, 'A', 'C', 'B');
long end = System.nanoTime();
out.println("Total Time: " + (end- start) + " nano seconds.");
System.out.println("Execution completed");
out.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started