Question

Recursion Write a program to solve the Towers of Hanoi problem for a tower of size n, using both recursion and iteration. Tim

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

`Hey,

Note: If you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

public class Test
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
System.out.println("Move disk 1 from tower " + from_rod + " to tower " + to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from tower " + from_rod + " to tower " + to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
  
// Driver method
public static void main(String args[])
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
}
}

M Inbox - gurkar (1) Input Funci | Computer Scie * <> Online Java Co My Q&A | Che X Kaun Nachdi ( x + - 0 % f = C tutorialspo

Time complexity is O(2^n)

Space needed is O(n) on the stack

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
Recursion Write a program to solve the Towers of Hanoi problem for a tower of size...
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
ADVERTISEMENT