how to solve the towers of hanoi puzzle

17
How to solve the Towers of Hanoi puzzle The Classical Towers of Hanoi - an initial position of all disks is on post 'A'. Fig. 1 The solution of the puzzle is to build the tower on post 'C'. Fig. 2 The Arbitrary Towers of Hanoi - at start, disks can be in any position provided that a bigger disk is never on top of the smaller one (see Fig. 3). At the end, disks should be in another arbitrary position. * ) Fig. 3 Solving the Tower of Hanoi 'Solution' shortest path

Upload: amitesh-sharma

Post on 21-Apr-2015

162 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: How to Solve the Towers of Hanoi Puzzle

How to solve the Towers of Hanoi puzzle

The Classical Towers of Hanoi - an initial position of all disks is on post 'A'.

Fig. 1

The solution of the puzzle is to build the tower on post 'C'.

Fig. 2

The Arbitrary Towers of Hanoi - at start, disks can be in any position provided that a bigger disk is never on top of the smaller one (see Fig. 3). At the end, disks should be in another arbitrary position.  * )

Fig. 3

Solving the Tower of Hanoi

'Solution' ≡ shortest path

Recursive Solution:

1. Identify biggest discrepancy (=disk N)

2. If moveable to goal peg Then move

Page 2: How to Solve the Towers of Hanoi Puzzle

      Else

3.   Subgoal: set-up (N−1)-disk tower on non-goal peg.

4. Go to 1.  ...

Some authors use the term "regular" position for any of the 3ndisk arrangements that obey the rule of no disk on top of a smaller disk, and "perfect" position for one of the 3 disk arrangements with all disks on a single peg. Then the above algorithm is optimal between a regular position and a perfect position, or between a perfect position and a regular position, but not between two regular positions.

P.K. Stockmeyer 

Solving the Tower of Hanoi - 'regular' to 'perfect'

Let's start thinking how to solve it.Let's, for the sake of clarity, assume that our goal is to set a 4 disk-high tower on peg 'C' - just like in the classical Towers of Hanoi (see Fig. 2).Let's assume we 'know' how to move a 'perfect' 3 disk-high tower. Then on the way of solving there is one special setup. Disk 4 is on peg 'A' and the 3 disk-high tower is on peg 'B' and target peg 'C' is empty.

Fig. 4

From that position we have to move disk 4 from 'A' to 'C' and move by some magic the 3 disk-high tower from 'B' to 'C'.

So think back. Forget the disks bigger than 3. Disk 3 is on peg 'C'. We need disk 3 on peg 'B'. To obtain that, we need disk 3 in place where it is now, free peg 'B' and disks 2 and 1 stacked on peg 'A'. So our goal now is to put disk 2 on peg 'A'.

Page 3: How to Solve the Towers of Hanoi Puzzle

Fig. 5

Forget for the moment disk 3 (see Fig. 6). To be able to put disk 2 on peg 'A' we need to empty peg 'A' (above the thin blue line), disks smaller than disk 2 stacked on peg 'B'. So, our goal now is to put disk 1 on peg 'B'.As we can see, this is an easy task because disk 1 has no disk above it and peg 'B' is free.

Fig. 6

So let's move it.

Fig. 7

The steps above are made by the algorithm implemented in Towers of Hanoi when one clicks the "Help me" button. This button-function makes analysis of the current position and generates only one single move which leads to the solution. It is by design.

When the 'Help me' button is clicked again, the algorithm repeats all steps of the analysis starting from the position of the biggest disk - in this example disk 4 - and generates the next move - disk 2 from peg 'C' to peg 'A'.

Page 4: How to Solve the Towers of Hanoi Puzzle

Fig. 8

If one needs a recursive or iterative algorithm which generates the series of moves for solving arbitrary Towers of Hanoi then one should use a kind of back track programming, that is to remember previous steps of the analysis and not to repeat the analysis of the Towers from the ground.

But this is another story.

*) Mind that this setup may be not on the shortest path between the start and the end of the classical Towers. This can happen if one has made some wrong moves while resolving the classical Towers.

Towers of Hanoi Puzzle

Towers of Hanoi (aka Tower of Hanoi) is a mathematical puzzle invented by a French Mathematician Edouard Lucas in 1983. Initially the game has few discs arranged in the increasing order of size in one of the tower like shown above. The number of discs can vary, but there are only three towers. The goal is to transfer the discs from one tower another tower. However you can move only one disk at a time and you can never place a bigger disc over a smaller disk. It is also understood that you can only take the top most disc from any given tower.While this site doesn't require any general knowledge (unlike who wants to be a millionaire or other trivia games) it does require an astute mind and logical thinking.

Solution

Before trying to understand the general algorithm used to solve Tower of Hanoi, it is always better to learn to solve Tower of Honoi with three or four discs. Once you master solving the puzzle with three or four discs, you can solve the same puzzle with more discs with the following algorithm.

1)Move the top N-1 disks from Source to Auxiliary tower,2)Move the Nth disk from Source to Destination tower,

Page 5: How to Solve the Towers of Hanoi Puzzle

3)Move the N-1 disks from Auxiliary tower to Destination tower.Transfering the top N-1 disks from Source to Auxiliary tower can again be thought as a fresh problem and can be solve in the same manner. So once you master solving Tower of Hanoi with three disks, you can solve it with any number of disks with the above algorithm.

Tower of Hanoi

The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. We are given a tower of eight disks (initially four in the applet below), initially stacked in increasing size on one of three pegs. The objective is to transfer the entire tower to one of the other pegs (the rightmost one in the applet below), moving only one disk at a time and never a larger one onto a smaller.

The puzzle is well known to students of Computer Science since it appears in virtually any introductory text on data structures or algorithms. Its solution touches on two important topics discussed later on:

recursive functions and stacks recurrence relations

The applet has several controls that allow one to select the number of disks and observe the solution in a Fast or Slow manner. To solve the puzzle drag disks from one peg to another following the rules. You can drop a disk on to a peg when its center is sufficiently close to the center of the peg. The applet expects you to move disks from the leftmost peg to the rightmost peg.

Buy this applet

What if applet does not run?

Recursive solution

Let call the three pegs Src (Source), Aux (Auxiliary) and Dst (Destination). To better understand and appreciate the following solution you should try solving the puzzle for small number of disks, say, 2,3, and, perhaps, 4. However one solves the problem, sooner or later the bottom disk will have to be moved from Src to Dst. At this point in time all the remaining disks will have to be stacked in decreasing size order on Aux. After moving the bottom disk from Src to Dst these disks will have to be moved from Aux to Dst. Therefore, for a given number N of disks, the problem appears to be solved if we know how to accomplish the following tasks:

Page 6: How to Solve the Towers of Hanoi Puzzle

1. Move the top N - 1 disks from Src to Aux (using Dst as an intermediary peg)

2. Move the bottom disk from Src to Dst3. Move N - 1 disks from Aux to Dst (using Src as an intermediary peg)

Assume there is a function Solve with four arguments - number of disks and three pegs (source, intermediary and destination - in this order). Then the body of the function might look like

Solve(N, Src, Aux, Dst) if N is 0 exit else Solve(N - 1, Src, Dst, Aux) Move from Src to Dst Solve(N - 1, Aux, Src, Dst)

This actually serves as the definition of the function Solve. The function is recursive in that it calls itself repeatedly with decreasing values of N until a terminating condition (in our case N = 0) has been met. To me the sheer simplicity of the solution is breathtaking. For N = 3 it translates into

1. Move from Src to Dst2. Move from Src to Aux3. Move from Dst to Aux4. Move from Src to Dst5. Move from Aux to Src6. Move from Aux to Dst7. Move from Src to Dst

Of course "Move" means moving the topmost disk. For N = 4 we get the following sequence

1. Move from Src to Aux2. Move from Src to Dst3. Move from Aux to Dst4. Move from Src to Aux5. Move from Dst to Src6. Move from Dst to Aux7. Move from Src to Aux8. Move from Src to Dst9. Move from Aux to Dst10.Move from Aux to Src11.Move from Dst to Src12.Move from Aux to Dst13.Move from Src to Aux14.Move from Src to Dst15.Move from Aux to Dst

Page 7: How to Solve the Towers of Hanoi Puzzle

Recurrence relations

Let TN be the minimum number of moves needed to solve the puzzle with N disks. From the previous section T3 = 7 and T4 = 15. One can easily convince oneself that T2 = 3 and T1 = 1. A trained mathematician would also note that T0 = 0. Now let us try to derive a general formula.

The recursive solution above involves moving twice (N - 1) disks from one peg to another and making one additional move in between. It then follows that

TN ≤ TN-1 + 1 + TN-1 = 2TN-1 + 1

The inequality suggests that it might be possible to move N disks with fewer than 2TN-1 + 1 moves. Which is actually not the case. Indeed, when the time comes to move the bottom disk, (N - 1) smaller disks will have been moved from Src to Aux in at least TN-1 moves. Since we are trying to use as few steps as possible, we may assume that that portion of the task took exactly TN-1 moves. It takes just one move to move the biggest disk from Src to Dst. One then needs exactly TN-1 more steps to finish the task. Therefore the minimum number of moves needed to solve the puzzle with N disks equalsTN-1 + 1 + TN-1 = 2TN-1 + 1 moves.

In other words,

TN = 2TN-1 + 1

Thus we can define the quantity TN as

T0 = 0TN = 2TN-1 + 1 for N > 0

We may compute T1 = 2T0 + 1 = 1, T2 = 2T1 + 1= 3, T3 = 2T2 + 1 = 7 and so on sequentially.

The above expression is known as a recurrence relation which, as you might have noticed, is but a recursive function. TN is defined in terms of only one of its preceding values. Other recurrence relations may be more complicated, for example, f(N) = 2f(N - 1) + 3f(N - 2). Recurrence relations appear under various guises in numerous branches of Mathematics and applications.

Returning to the definition of TN, define SN = TN + 1. Then S0 = 1 and SN = TN + 1 = (2TN-1 + 1) + 1 = 2TN-1 + 2 = 2(TN-1 + 1) = 2SN-1. Which is to say that SN could be defined as

S0 = 1SN = 2SN-1 for N > 0

Page 8: How to Solve the Towers of Hanoi Puzzle

The latter is solved easily in the closed (non-recurrent) form SN=2N. Wherefrom

TN = 2N - 1 for N ≥ 0.

#include<iostream.h>#include<stdio.h>#include<conio.h>

class tower{int *t1,*t2,*t3;int x,y,z;public:void disp_tower();void move_disk(int tx,int ty);void toh(int n,int a,int b,int c);tower(int no);~tower();};

tower :: tower(int no){t1 = new int[no+1];t2 = new int[no+1];t3 = new int[no+1];x = no;y = z = 0;

for(int i=0,j=no ; i<no ; i++,j--){t1[i] = j;t2[i] = t2[i] = 0;}t1[no] = t2[no] = t3[no] = 0;}

tower :: ~tower()

Page 9: How to Solve the Towers of Hanoi Puzzle

{delete []t1;delete []t2;delete []t3;}void tower :: disp_tower(){clrscr();cout<<"

X :: ";for(int i=0;i<x;i++){cout<<" "<<t1[i];}cout<<"

Y :: ";for(i=0;i<y;i++){cout<<" "<<t2[i];}cout<<"

Z :: ";for(i=0;i<z;i++){cout<<" "<<t3[i];}getch();}

void tower :: toh(int n,int tx,int ty,int tz) //x to y using z{

if(n>=1)

Page 10: How to Solve the Towers of Hanoi Puzzle

{toh(n-1,tx,tz,ty);move_disk(tx,ty); //x to ydisp_tower();toh(n-1,tz,ty,tx);}}

void tower :: move_disk(int tx,int ty){switch(tx){case 1:{if(ty==2)t2[y++] = t1[--x];elset3[z++] = t1[--x];}break;case 2:{if(ty==1)t1[x++] = t2[--y];elset3[z++] = t2[--y];}break;case 3:{if(ty==1)t1[x++] = t3[--z];elset2[y++] = t3[--z];}break;}//end of switch}//------------------------------------------------------------------------

Page 11: How to Solve the Towers of Hanoi Puzzle

---int main(void){clrscr();cout<<"Enter the no. of disks::";int no;cin>>no;tower obj(no);obj.disp_tower();obj.toh(no,1,2,3);getch();return 0;}

      The Tower of Hanoi is one of the truly classic puzzle games, challenging players with its

seemingly simple but frustratingly difficult goal. In the Tower of Hanoi puzzle a player attempts to

move a large pile of disks, known as the Tower, from the leftmost peg to the rightmost on the

puzzle board. The rules of the puzzle state that the player can only move one disk per turn and

can never place a larger disk onto a smaller one at any time.

      Based on these guidelines, players attempt to move their initial Tower disk-by-disk towards

the target third peg in a seemingly complex method of movement using any of the three

available pegs until it is rebuilt onto the rightmost peg exactly as it was on the initial leftmost peg

at the start of the puzzle. The puzzle was invented by the French mathematician Edouard Lucas

in 1883 and is often described as a mathematical puzzle, although solving the Tower of Hanoi

doesn't require any mathematical equations at all for a human player. In fact,

the ChessandPoker.com Tower of Hanoi solution provides two simple algorithms that allow

players to optimally solve Tower of Hanoi puzzles with any number of disks when applied to the

puzzle!

Optimal Algorithms for Solving Tower of Hanoi Puzzles

      Tower of Hanoi Puzzles may consist of

any number of disks as long as they total three or more. The most common total of disks is

seven, but you may have puzzles with more (or less) disks in play. The proper solution for a

Tower of Hanoi puzzle is very similar for all of the various puzzles, but varies slightly based on

whether or not the total number of disks in the puzzle is Odd or Even. In this guide we'll focus on

solving a seven-disk Tower of Hanoi puzzle and we've provided an example of our puzzle board in

the graphic above, complete with colored disks for reference purposes.

Page 12: How to Solve the Towers of Hanoi Puzzle

      In our solution algorithms below we'll focus mainly on the top three disks of the Tower. These

three disks are moved around quite a bit in an optimal solution, so it will be necessary to become

familiar with them. The topmost disk is known as Disk 1. It is colored Red in our graphic and is the

smallest of all the disks. The second disk from the top is called Disk 2. It is the second smallest

disk in the puzzle and is colored Orange in our examples. Finally, the third disk down is called

Disk 3 and is colored Yellow. The remaining disks of various colors are simply known as Big Disks,

and numbering them is not necessary. We'll now take a look at the algorithms used to solve the

Tower of Hanoi and how these three focus disks will factor into each solution.

Odd Number of Disks Even Number of Disks

1. Move Disk 1 to the LEFT2. Move Disk 2 (only move)3. Move Disk 1 to the LEFT4. Move Disk 3 (only move)5. Move Disk 1 to the LEFT6. Move Disk 2 (only move)7. Move Disk 1 to the LEFT8. Move a Big Disk

1. Move Disk 1 to the RIGHT2. Move Disk 2 (only move)3. Move Disk 1 to the RIGHT4. Move Disk 3 (only move)5. Move Disk 1 to the RIGHT6. Move Disk 2 (only move)7. Move Disk 1 to the RIGHT8. Move a Big Disk

      In the chart to the left you'll find the two optimal move algorithms for any Tower of Hanoi

puzzles based on the total number of disks in your starting Tower. The leftmost column shows the

move algorithm for puzzles with an odd number of disks, and the rightmost column details the

solution for puzzles with an even number of starting disks. In our guide we'll be using the "odd"

algorithm since our example puzzle contains seven disks. To solve their puzzle a player will

perform the applicable 8-move algorithm to their board repeatedly until all of the disks have been

transferred from the leftmost starting peg to the rightmost target peg.

      The two algorithms share some notable

similarities, particularly that the tiny Disk 1 is repositioned on every other move in an optimal

solution. For example, the odd algorithm has it moving one peg to the left on steps 1, 3, 5 and 7.

So if Disk 1 currently resides on the right most peg, it would move one peg to the left to the

middle peg on its turn. And if it was instead resting on the middle peg it would move one peg to

the left onto the leftmost peg. But what if it is already on the leftmost peg? As we can see in our

movement graphic above, you may think of the Disk 1 movements across the board as a circular

motion. If Disk 1 is on the leftmost peg, moving it left would bring it back around to the right most

peg. This completes the circle of movement and would once again allow Disk 1 to move left onto

the middle peg and then back onto the leftmost peg again, ready to jump back around to the

rightmost peg and start the sequence again. Of course, for puzzles with an Even number of disks

the movements would be reversed but would follow the same pattern. Disk 1 would jump from

the leftmost peg to the right, landing on the middle peg. From the middle peg it would move right

onto the rightmost peg, and then back around to the leftmost peg again to complete the circular

sequence.

Page 13: How to Solve the Towers of Hanoi Puzzle

      We'll now take a look at the first application of our algorithm to the seven-disk Tower of Hanoi

board, which will start us on our way towards the optimal solution for the puzzle. An optimal

solution solves the applicable Tower of Hanoi puzzle in the least possible number of moves. By

using our algorithms, the player is assured that their solution will always be optimal since it

efficiently ensures that there are no wasted maneuvers of any disks!

How to Solve a Seven-Disk Tower of Hanoi Puzzle

Step One - Move Disk 1 to the Left: The

first step in the "odd" puzzle algorithm instructs us to move Disk 1 to the left. As we've just

discussed, whenever Disk 1 is on the leftmost peg moving it left entails looping it back around to

the rightmost peg to complete the circular left-to-right motion. As you can see in the graphic,

Step 1 has been performed and now shows Disk 1 on the target rightmost peg.

Step Two - Move Disk 2: On Step 2 we're

informed that we need to move Orange Disk 2, but it doesn't say where to move it. However, a

closer examination of the board shows us that, based on the rule that a player may not place a

bigger disk onto a smaller one, Disk 2 only has one legal move. We can confidently move Disk 2

to the middle peg to complete the step. In fact, Disk 2 will always only have one legal move.

Step Three - Move Disk 1 to the Left:

The third step once again has tiny Disk 1 moving itself to the left, which means that this time it

will be jumping onto Disk 2 which just moved there on our previous step. This is a legal move, of

course, since Disk 1 is smaller than Disk 2. It's useful to note that Disk 1 will frequently be moving

onto Disk 2. In fact, it does so twice in each algorithm on steps 3 and 7.

Step Four - Move Disk 3: Step 4 has us moving Yellow Disk 3 for the first time in the

algorithm. As is the case for Disk 2, there will always only be one legal move available for Disk 3

when using our algorithms. Since Disk 3 cannot be placed on the peg containing the smaller Disk

1 as the topmost disk, the only peg Disk 3 can claim residence on is the rightmost peg. Our

graphic shows the board after this move has been played.

Page 14: How to Solve the Towers of Hanoi Puzzle

Step Five - Move Disk 1 to the Left: As

you've no doubt now become acquainted with, Step 5 requires Disk 1 to yet again be moved one

peg to the left. For those players with an eye for patterns, you may notice that Disk 1 doesn't

seem to like Disk 3. In fact, if you're applying the algorithm correctly you'll actually never be

placing Disk 1 onto Disk three. It always moves onto Disk 2 or a Big Disk.

Step Six - Move Disk 2: Step 6 brings

about another movement for Disk 2, which once again has only one legal move available to it,

this time hopping onto Yellow Disk 3. More patterns? Indeed, it would appear that each step in

the algorithm so far has been working to rebuild the Disk 1-2-3 section of the initial tower. The

next move will of course complete the construction and bring us closer to the end of the

algorithm.

Step Seven - Move Disk 1 to the Left:

Disk 1 moves to the left, looping back around to the rightmost peg and preparing for the final

move of the first run-through of the algorithm. If we were just solving a three-disk Tower of Hanoi,

the puzzle would already be solved at this point! But with more disks to go, we'll need to proceed

to the final step of the algorithm before we'll be ready for another application.

Step Eight - Move a Big Disk: Up to this

point, we've only been moving the smallest three disks back and forth on top of one another.

Now that their mini-tower has been rebuilt by the algorithm, it's time to move a Big Disk. The big

disk that has a legal move available to it would in this case be the Green Disk. Step 8 will always

feature a completed mini-tower and only one big disk with a legal move. That's it for the first run-

through!

Multiple Algorithm Applications

      After finishing Step 8, the first application of the algorithm is complete. To continue

the solution, the odd algorithm must once again be performed in its entirety. Move Disk 1 to the

left, move Disk 2, move Disk 1 to the left again, move Disk 3, move Disk 1 to the left for the third

time, move disk 2, move Disk 1 to the left and finally move the next Big Disk (in this case it's the

Light-Blue disk). The graphic above shows the board after the second run-through of the

Page 15: How to Solve the Towers of Hanoi Puzzle

algorithm so you'll be able to verify that your technique is correct. Now that you've got the hang

of it, continue to apply the algorithm until your Tower of Hanoi puzzle is completely solved. Of

course, if your starting tower has an even number of disks you'll need to use the alternate "Even"

algorithm to solve the puzzle, which follows the same process but in the opposite direction.

Complete each of the eight steps before restarting the algorithm, and eventually you'll have a

completely solved Tower of Hanoi!

ChessandPoker.com Browsing Options

      Thank you for reading this featured game article! Please select one of the links below to

continue navigating theChess and Poker Dot Com website. Let us know if we can be of any

further help. Good luck and happy gaming!