Last answered:

07 Dec 2021

Posted on:

07 Dec 2021

0

How a smaller disc can be added on top of a bigger disc but not vise versa?

Somehow, I could not follow the answer here, and found myself very confused after rewatching the video, watching other recursive functions videos on YouTube. I conceptually understand the logic of the algorithm, I understand how you need to move n-1 disc to tower B first, before moving the nth disc to tower C, so on and so forth.  However, I just don't see how the next three lines of code after the "else" line can achieve exactly what it needs to be achieved. In addition, how does this code satisfy the requirement that only smaller disc can be added on top of a bigger disc but not vise versa?

1 answers ( 0 marked as helpful)
Posted on:

07 Dec 2021

0

If I understand correctly, the code that is listed under "if n ==1", is executed n times in a row, for all of the n disks, but every time it is executed, the start tower, the intermediate tower and the destination tower are switched around so that each disk in a row is moved to a different tower. The call stack is built up starting with the highest number disk at the bottom and ending with the lowest number disk at the top, until at the top of the call stack we end up with our disk 1. When the call stack is complete, then the returns of the function are handled, starting from the top of the call stack, and ranging to the bottom of the call stack. So, the returns start at disk 1, for which the base case is executed, and then that is popped from the call stack, at which point the base case is executed for disk 2 which is then at the top of the call stack, etc.

Submit an answer