# Examples of Recursion

### Towers of Hanoi

#### What are the Towers of Hanoi?

Is the end of the world near? At a monastery in the city of Hanoi, Vietnam, a group of monks has made it their life's work to solve the Towers problem, known due to its location as the Towers of Hanoi. Legend has it that the world will end when the monks finally solve the puzzle.

The puzzle is this. In the monastery are 3 pegs made of diamond. Resting on these pegs are 64 discs made of solid gold. None of the 64 discs are the same size; in fact, disc 1 is slightly larger in diameter than disc 2, which is slightly larger in diameter than disc 3, which is slightly larger in diameter than disc 4, etc. The initial configuration of the puzzle has all 64 discs piled in order of size on the first peg with the largest disc on the bottom.

Figure %: Example Towers Configuration

To solve the puzzle, all 64 discs must be moved to the third peg. Easy you say? The problem is that due to the fragility of the gold, you are not allowed to rest a larger disc on top of a smaller one, and only one disc may be removed from the pegs at any one time.

Figure %: Moving a single disc

There are many ways to solve this problem. The first is purely guess and check. Those who fear the end of the world may be hoping that the monks are using this approach. However, they're not; in fact, the monks all know the exact sequence of moves to solve the problem.

#### Solving Towers of Hanoi

##### One Disc

Let's simplify the problem to clarify our thinking. Let's imagine the Towers of Hanoi problem with only one disc.

Figure %: Towers Problem with 1 Disc

How do we solve this problem? Simple. We just move the disc on the first pole to the third pole.

Figure %: Towers Solution for 1 disc
##### Two Discs

Let's make the problem slightly bigger. Imagine two discs.

Figure %: Towers Problem with 2 Discs

How do we solve this problem? Simple, again.

1. Use the one disc solution to move the top disc to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the one disc solution to move the top disc to the final pole.

Figure %: Towers Solution for 2 Discs
##### Three Discs

How about with three discs?

1. Use the two disc solution to move the top discs to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the two disc solution to move the top discs to the final pole.

##### N Discs

So how about with N Discs?

1. Use the N - 1 disc solution to move the top discs to the intermediate pole.
2. Use the one disc solution to move the bottom disc to the final pole.
3. Use the N - 1 disc solution to move the top discs to the final pole.

Figure %: Towers Solution for N discs

And, voila! A recursive solution to solving the Towers of Hanoi! Note that the problem can be solved iteratively as well; however it makes much more intuitive sense recursively.

#### Coding Towers of Hanoi

Now that we know how to solve an n -disc problem, let's turn this into an algorithm we can use.

If there is one disc, then we move 1 disc from the source pole to the destination pole. Otherwise, we move n - 1 discs from the source pole to the temporary pole, we move 1 disc from the source pole to the destination pole, and we finish by moving the n - 1 discs from the temporary pole to the destination pole.

```
void TOH(int n, int p1, int p2, int p3)
{
if (n == 1) printf("Move top disc from %d to %d.\n", p1, p2);
else {
TOH(n-1, p1, p3, p2);
printf("Move top disc from %d to %d.\n", p1, p2);
TOH(n-1, p3, p2, p1);
}
}
```

Of course, we can simplify this to the following:

```
void TOH(int n, int p1, int p2, int p3)
{
if (n>1) TOH(n-1, p1, p3, p2);
printf("Move top disc from %d to %d.\n", p1, p2);
if (n>1) TOH(n-1, p3, p2, p1);
}
```

Pretty cool, huh? This example shows the power of recursion to turn what seems like a hard and intricate problem into something much more simple that can be solved in three lines of code.

#### Will the World End Tomorrow?

Actually, the whole story of the monks is just a legend. In fact, it isn't even an old legend. The story was created in 1883 by a mathematician named Edouard Lucas. He had invented an eight disc, three tower puzzle, and created the legend in order to sell his product.

That being said, what if the story were true? Should we be worried about the world ending when the monks solve the puzzle? After all, they live in the 21st century, too, and have access to the same information about recursion that we have.

Luckily, just as mathematics helps us solve the puzzle, it also helps prove that our grandchildren will still have a world to live in. In order to figure out how long it will take the monks to solve the puzzle, we need to write a recurrence relation, a recursive formula for describing the size of a recursive problem. Let's call our recursive formula T(n), where n is the number of discs.

As seen above, the base case for the Towers of Hanoi problem is when n is 1. This is when the monks just have to move one disc from one pole to another. So T(1) = 1 . For the recursive case where n! = 1 , we need a more complicated formula. The monks, in the recursive case, follow a three step procedure. They move n - 1 discs, then they move 1 disc, and then they move n - 1 discs. So T(n) = T(n - 1) + T(1) + T(n - 1) = 2T(n - 1) + 1 .

Now we know that to solve a Towers problem with n discs takes T(n) = 2T(n - 1) + 1 steps. It would be nice if we had a closed-form solution to this recurrence so that we could figure out exactly how long it will take. A closed form solution is a formula without recursion, meaning we can simply plug in numbers and get our answer.

Let's plug in some sizes and solve the Towers problem with those sizes to see if we can find a closed-form solution.

• T(1) = 1
• T(2) = 3
• T(3) = 7
• T(4) = 15
• T(5) = 31
• T(6) = 63
• T(7) = 127
• T(8) = 255
• T(9) = 511
• T(10) = 1023
Notice a pattern here? T(n) = 2n - 1 . To prove to yourself that this is true, try modifying your TOH code to count the number of disc moves. Create a global variable count, run your modified TOH code, and then print out count.

Now we can easily compute how long it would take the monks to solve their 64-disc Towers problem. 264 - 1 is approximately 18.45x1018 (note that if you actually tried to run the TOH code on your computer it would most likely take a very, very long time). If the monks could move a disc in a millisecond (an incredibly rate considering the size and weight of each disc), it would take them approximately 584,600,000 years to solve the puzzle. It appears the world is safe for now.

## Take a Study Break

### Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

### Are you afraid of relationships?

Auntie SparkNotes can help!

### Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

### Sexy starlet style

See every single look from the Met Gala!

### Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Before the fame!

### 9 Scientific Inaccuracies in Iron Man 3

Click to see what they got wrong.

### Top 10 Predictions Sci-Fi Got WRONG

So wrong, they're WRONG.

### The 15 Most Awesome Robots, Ever

These Robots Rock!

### If You Like Game of Thrones...

...Then you'll LOVE these books!

## The Book

### Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps