• Create Account

# Tower of Hanoi Recursively in c++ (long)

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

7 replies to this topic

### #1stembro  Members   -  Reputation: 798

Like
0Likes
Like

Posted 01 January 2005 - 07:46 AM

Alright, so everything was going smooth with this book I'm reading (Data Structures for Game Programmers) until I got to the chapter on recursion. The first problem the author wants you to figure out is solving x to the nth power recursively. Alright, simple enough. I figured that one out pretty quickly, and thought that the next problem couldn't be any harder than that... Pseudo Code: (n = total blocks, s = start pole, d = dest pole, o = open pole)
Hanoi(n, s, d, o)
if(n > 0)
Hanoi(n-1, s, o d);
Print "Moving n from s to d."
Hanoi(n-1, o, d, s)

Example with calling Hanoi( 3, 1, 3, 2) prints out:
1    2   3
============
1  |   |   |
2  |   |   |
3  |   |   |

Step 1: Moving 1 from 1 to 3.
1    2   3
============
|   |   |
2  |   |   |
3  |   | 1 |

Step 2: Moving 2 from 1 to 2.
1    2   3
============
|   |   |
|   |   |
3  | 2 | 1 |

Step 3: Moving 1 from 3 to 2.
1    2   3
============
|   |   |
| 1 |   |
3  | 2 |   |

Step 4: Moving 3 from 1 to 3.
1    2   3
============
|   |   |
| 1 |   |
| 2 | 3 |

Step 5: Moving 1 from 2 to 1.
1    2   3
============
|   |   |
|   |   |
1 | 2 | 3 |

Step 6: Moving 2 from 2 to 3.
1    2   3
============
|   |   |
|   | 2 |
1 |   | 3 |

Step 7: Moving 1 from 1 to 3.
1    2   3
============
|   | 1 |
|   | 2 |
|   | 3 |

( 2^n - 1 moves)


35 minutes later, I'm still trying to figure out why the tower of hanoi recursive algorithm works. Basically, it looks like this:
void Hanoi(int numberOfBlocks, int startPole, int destPole, int openPole)
{
if( numberOfBlocks > 0 )
{
// openPole and destPole are swapped
Hanoi(numberOfBlocks - 1, startPole, openPole, destPole);

cout << "Moving " << n << " from " << startPole;
cout << " to " << destPole << endl;

// openPole and startPole are swapped
Hanoi(numberOfBlocks - 1, openPole, destPole, startPole);
}
}


Alright, so I'll be passing in the total number of blocks to move, the starting pole those blocks are on, the final pole where they should end up, and the open pole. Lets say I have three blocks total, located on pole #1. I have a total of three poles, with #3 being the destination and #2 being the open pole. I want to move all 3 blocks to #3. So I call the Hanoi function like this:
Hanoi( 3, 1, 3, 2);


In the function, the if statement checks if numberOfBlocks is > 0, which it is, and then calls Hanoi again with numberOfBlocks - 1. The if statement gets checked again, and now numberOfBlocks = 2, so Hanoi is called again with numberOfBlocks - 1, and the if statement gets checked again seeing that numberOfBlocks now equals 1. Pretty simple recursion at this point. After the next call the function will start returning because the if statement will be false, and then cout will be called for the results of the second recursion (where n = 1). Then Hanoi is called again, until n = 0. Original call: ( 3, 1, 3, 2 ); // n, s, d, o 1. (2, 1, 2, 3 ); // n, s, o, d 2. (1, 1, 2, 3 ); 3. (0, 1, 2, 3 ); // if statement fails, function returns back to step 2 ------ And this is where I'm getting lost. After the third call's if statement fails, it returns back to step 2, where the first message is printed and Hanoi is called again. This time, the openPole and startPole values are swapped, so the call should look like this: 4. ( 1 (?), 2, 3, 1) // n, o, d, s At this point, what is the value of n that is passed into the function? At step 2, n = 2, so I'm assuming that the ? in step 4 should be 2-1, or just 1. Which starts the entire thing again because the if statement is true. So, after each time the second hanoi function is called, it goes through the first few steps again. At this point, short of writing out /every/ step on a few sheets of paper, I don't see how it actually moves the correct pieces in the correct order. I'm really close to just pulling out a pad of paper and writing down each and every function call and the values involved, but I'm hoping someone who already understands how this works can help me out a bit. I understand how recursion works, but I don't understand how and why this algorithm does what it does.

### #2Snaily  Members   -  Reputation: 151

Like
0Likes
Like

Posted 01 January 2005 - 07:54 AM

The way I thought about this recursive problem is that the function is a guide on how to move a stack of blocks from one pole to another - as long as I know how to move a (n-1) sized stack, moving a n sized one is easy: move all blocks but the one furthest down ((n-1) block) to the open pole, then move the last block to the final pole, then move the stack back on top of it.

### #3stembro  Members   -  Reputation: 798

Like
0Likes
Like

Posted 01 January 2005 - 08:13 AM

Yea, I see what you mean. So:

1    2   3===========     ->   ==========     =>    ==========   |   |                |   |                |   | 1   | 1 |                | 1 |                |   | 2 3 | 2 |                | 2 | 3              |   | 3

Which is

Moving n discs
---------------
"move the top n-1 blocks to pillar 2"
"move the nth block tp pillar 3"
"move the n-1 blocks to pillar 3"

And I understand that (well, its easy to follow because everything is being moved in "chunks").

Moving n-1 discs
----------------
"move the top n-2 block (for 3 blocks, this is block 1) to pillar 3"
"move the n-1 block (block 2) to pillar 2"
"move the n-2 block (block 1) from pillar 3 (step 1) to pillar 2"

Which is fine, it's just moving one block at a time instead of moving them in chunks.

And the function is doing this recursively:

1. moves the top n-1 discs from the starting pillar onto the open pillar
2. moves the nth disc from the starting pillar to the destination pillar
3. moves the top n-1 discs from the open pillar to the destination pillar

And I get that too.. but I don't get how it actually /works/ recursively!

I think I need to just write all of the steps down on a sheet of paper so I can follow the entire thing step by step.

### #4Nice Coder  Members   -  Reputation: 366

Like
0Likes
Like

Posted 01 January 2005 - 01:14 PM

Ah i think you could do a bit better then that.

hanoi (board, goal, moveslist)	if board is = goal then return moveslist	make a list of all moves that are movable from board, and put them into l1	Evaluate how close each of them are to the goal state, and sort them by it. (so really close states come before other states, ect).	Make a new board B2	In order of how close they are to the goal state, counter x		Make b2, equal to board		Make the xth move on l1, on b2 (so you make the move that the xth element on l1 says, on b2)		call hanoi (b2, goal)		if hanoi returned a moveslist then			add the x'th element of b2 to the beginning of moveslist			return moveslist		end if	end order	Return falure

Now, figure out HOW it works, WHY it works, then from scratch make another ENTIRELY DIFFERENT one. Also figure out why yours DIDN"T work, what is WRONG with it, and use that to fix your version.

Also, try to make a recurcive version of a* to solve this problem.
Its pretty easy once you get around to it (its just another set of values to sort by, an extra argument for the function, and a bit of math (not much tho))

From,
Nice coder

[Edited by - Nice Coder on January 1, 2005 7:14:21 PM]

### #5misterX  Members   -  Reputation: 144

Like
0Likes
Like

Posted 03 January 2005 - 11:59 AM

to nice coder:
*bump*, what are you talking about?!

to onTheHeap:
the first time i saw this, i didn't post a reply because the way it works is so obvious that i couldn't even explain it. So i'll just repeat what you and Snaily said.

The recursive procedure is like follow:
(1) Hanoi(n, s, d, o)
(2) if(n > 0)
(3) Hanoi(n-1, s, o d);
(4) Print "Moving n from s to d."
(5) Hanoi(n-1, o, d, s)

(1) What does this procedure do: it moves the upper N blocks from S to D using O as temporary pillar.
(2) the condition: if n=0, it means no blocks must be moved, so do nothing
(3) move the upper N-1 blocks from here to the open pillar, where the destination pillar can for the moment be used as the temporary pillar.
(4) move the current block to D
(5) move the stack on the open pillar back to the destination pillar.

Ok, that's clear, you've already catched it, i'm just repeating what you already know.

So, why does it work? ...let's do a bit logic and you'll see.

First, let's proove it works for a single block (n=1) (*)
Hanoi (1, s, d, o) will work since:

Hanoi(0, s, o d); => this call will do nothing
Print "Moving n from s to d." => the block is moved as expected
Hanoi(0, o, d, s) => this call will do nothing

Now, let's assume it works also for n blocks! We'll now try to prove that it'll also work for n+1 blocks: (**)

Hanoi (n+1, s, d, o)
Hanoi(n, s, o d); => By hypothesis, it is meant to work correctly and moves the n upper blocks to the open pillar
Print "Moving n from s to d." => the block is moved to the destination
Hanoi(n-1, o, d, s) => By hypothesis, it is meant to work correctly and moves the n upper blocks back from the open pillar onto the destination pillar
=> Therefore, as we have proven, if it works for n blocks then it'll also work for n+1 blocks.

Now let's combine (*) and (**).
Since it works for 1 block, it'll also work for 2 blocks and since it works for 2 block, it'll also work for 3 blocks... and so on. I think you got it.

This may sound a bit complicated at first but in fact, it's incredibly simple.

But this is nearly a mathematical explanation. What is important to get is really being able to "think recursively", once you have your mind thinking this way, you'll see the incredible simplicity and power of recursiviness. Isn't the hanoi example an elegant and simple solution after all? Once you got it, you won't need explanations or proofs anymore, nor even think more than a minute to solve problems like these.

(PS: sometimes, i really wonder why i'm rated downwards (i'm good after all) and see people like nice coder telling bullshit have good ratings... idiot forums!)

### #6stembro  Members   -  Reputation: 798

Like
0Likes
Like

Posted 03 January 2005 - 01:42 PM

misterX, ratings++

I wrote a really simple app yesterday that pauses at each step and prints out a bit of information regarding the current values for each of the variables and what values the hanoi function was called with. Made it a lot easier to see just what exactly was going on.

The recursive solution to this problem is nothing short of astounding! This is the first real recursive problem I've looked at (other than the common fibonacci numbers, and x to the y power examples). Really cool stuff.

### #7Nice Coder  Members   -  Reputation: 366

Like
0Likes
Like

Posted 03 January 2005 - 02:44 PM

Misterx: Oh. You hurt my feelings........ Mean.

And for the record: Thats psudocode for a recursive greedy search that i used to do the towers problem, until i found a*.

From,
Nice coder

### #8Álvaro  Crossbones+   -  Reputation: 19099

Like
0Likes
Like

Posted 03 January 2005 - 03:59 PM

A non-recursive solution to this problem is as follows:
*on odd-numbered moves, move the smallest disk to the next peg (from 1 to 2, from 2 to 3 and from 3 to 1).
*on even-numbered moves, make the only possible move that does not involve the smallest disk.

Try it!

(if you get the final stack in the wrong place, try moving the smallest disk in the opposite direction: 1=>3, 2=>1, 3=>2)

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS