
Now we can break down the problem to the following. Then we have that all n disks start on tower (rod) 0 and should end in tower (rod) 2. If we number the towers (rods) 0, 1, and 2. This means that the problem starts with n disks.
#RECURSIVE HANOI TOWERS CODE#
It will make your code easy and straight forward. The example of Tower of Hanoi will show you the benefit. The above might not be a good example of how recursion helps you. Well, what did we gain from making the function recursive? Let’s first try to do in the iterative way. It can be a bit difficult to connect the definition of recursions to getting the sum of the integers 1 + 2+ 3 + … + (n – 1) + n. While that is a beautiful and perfect definition – there is still need to exemplify what that means.Ī simple example is to sum up the numbers from 1 to n. Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Step 2: Recall recursion and unleash the power of it

Now do yourself a favor and try to think how you would solve that. The third rule says, that we cannot move disk 2 on top of disk 1. Say, in the above we have moved the disk 1 from the first to the second tower (rod).Īfter that move, we can move disk 2 or disk 1. The first two rules combined means that you can only take one top disk and move it. You cannot place a bigger disk on top of a smaller disk.You can only take the top disk and place on top of another tower (rod).

You can only move one disk at the time.The goal is to move all the disks from on tower (rod) to another one with the following 3 rules. The disk all have different sizes as pictured above. A basic setup of Tower of Hanoi with 3 disks and 3 towers (often called rods) Before we set the rules, let’s see how our universe looks like. Tower of Hanoi is a mathematical game, which has three rules.

Step 1: Understand the Tower of Hanoi challenge
