Question

Please write a recursive Java program to solve the Tower of Hanoi game for n disks...

Please write a recursive Java program to solve the Tower of Hanoi game for n disks on pole A. Please read the textbook page 176 – 180 to fully understand this game or puzzle.

The game consists of n disks and three poles: A (the source), B (the destination), and C (the spare). Initially, all the disks are on pole A. The game is to move all disks (one by one) from pole A to pole B using pole C as a temporary transfer area during the moves. At any given time, a disk can be placed only on top of a disk that is larger than itself. As you can see, you must write a recursive program to solve this game.

You must run 3 test cases for your program.   For your test case # 1, n is 3.   For your test case # 2, n is 4.    For your test case # 3, n is 5.

The output of your test case #1 (n = 3 disks on pole A) must look as follows: (also shown on page 179)

Move top disk from pole A to pole B.   

Move top disk from pole A to pole C.   

Move top disk from pole B to pole C.   

Move top disk from pole A to pole B.   

Move top disk from pole C to pole A.   

Move top disk from pole C to pole B.   

Move top disk from pole A to pole B.   

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java Program:

class Main {

static void towerOfHanoi(int a, char fpole, char tpole, char apole)

{

if (a==1)

{

System.out.println("Move disk 1 from pole " + fpole + " to pole " + tpole);

return;

}

towerOfHanoi(a-1,fpole,apole,tpole);

System.out.println("Move disk " + a + " from pole " +fpole+ " to pole " + tpole);

towerOfHanoi(a-1, apole, tpole, fpole);

}

public static void main(String args[])

{

int n=3;

towerOfHanoi(n, 'A', 'C', 'B');

}

}

if you like the answer please provide a thumbs up.

Add a comment
Know the answer?
Add Answer to:
Please write a recursive Java program to solve the Tower of Hanoi game for n disks...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT