First of all, thanks for asking an intellectual question. Don't get to see these often and I, personally, absolutely love to talk about these. I would like you to understand it yourself and I am sure you can. I will only explain the code a bit more to help you out.

(Assuming you know what a Tower of Hanoi[^] puzzle is...)

In short - Recursion means invoking itself. Or the repeated application of the same procedure on itself.

In your example, the method Hanoi is invoking itself for certain number of times and eventually

solving itself[^] which is why it is a recursive procedure or method.

In your code, Towers are the rods and n(=3) is the number of discs. Here is the logic your code follows every time the Hanoi method is called:

To move n discs from Tower 1 to Tower 3

move n−1 discs from Tower 1 to Tower 2. This leaves disc n alone on Tower 1.

move disc n from Tower 1 to Tower 3

move n−1 discs from Tower 2 to Tower 3 so they sit on disc n

Now go ahead and put a break point in Hanoi() and keep doing F10 until you understand it. Put watches on Tower1, Tower2, Tower3 and n which will help you.

If stuck, write back. Happy Coding.

Also, if you are a lover of programming puzzles like me, please see this[^]

[Please accept/up-vote answers or solutions that work for you to encourage others]

15,506,209 members

—SA

call n=3 t1=1 t2=2 t3=3 a=1

call n=2 t1=1 t2=3 t3=2 a=1

call n=1 t1=1 t2=2 t3=3 a=1

Move from 1 to 3

call n=1 t1=1 t2=3 t3=2 a=2

Move from 1 to 2

call n=1 t1=3 t2=1 t3=2 a=3

Move from 3 to 2

call n=1 t1=1 t2=2 t3=3 a=2

Move from 1 to 3

call n=2 t1=2 t2=1 t3=3 a=3

call n=1 t1=2 t2=3 t3=1 a=1

Move from 2 to 1

call n=1 t1=2 t2=1 t3=3 a=2

Move from 2 to 3

call n=1 t1=1 t2=2 t3=3 a=3

Move from 1 to 3