Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Object Databases The Essentials

Authors: Mary E. S. Loomis

1st Edition

020156341X, 978-0201563412

More Books

Students also viewed these Databases questions