Pages

Tuesday, October 12, 2010

Hanoi Algo

                       Tower  Of  Hanoi

Tower of Hanoi is a mathematical game or puzzle invented by french mathematician in 1983.

a)It consists of three rods, suppose A , B , C . And contains a number of disks of different sizes which can slide from one rod to another.
b)Disks are arranged in ascending order from the top i.e. smallest one is at the top.
(No need to confuse you are thinking that all three rods contains disks......Absolutely No....Actually the first Rod(A) contains the disks in ascending order and our goal is to move or transfer or arrange all disks from rod A to Rod C in ascending order via rod B )

now we have fixed no of tower i.e.3 but the no of disks varies up to 9(max no disks) .....................
if we have 3 disks then we have to complete in 7 moves only.....
samer as  for  4= 15 moves
               5=31 moves
               6=63 moves
............................
.............................
i.e. in general 2^n-1 , where n=no of disks.

We have to follow the following rules for moving disks......

1)Only one disk may be moved at a time
2)Each move consists of taking the upper disk frm one of the rod and sliding it onto another rod.
3)No disk may be placed on top of a smaller disk.

First u try by taking 3 disks.... Once you become master in solving the game with 3 disks then u can solve it for any no of disks.......

for n= 3
1)A -> c
2)A -> B
3)C -> B
4)A -> C
5)B -> A
6)B -> C
7)A -> c


http://www.towerofhanoi.net/
We have 7 valid moves.

Some tips:
(Alternate moves between the smallest disk and a non smallest disk, when smallest disk alw  moving the s)ays move it in the same direction)  ..... leave it if u not understood.

see.... if the starting no of disk is even (4,6...) move to the right..... if the starting no of disk is odd move it to the left.... if there is no rod in the chosen direction i.e. left move it to the opposite end but further move it in correct direction to compensate...........

See in general........................
1)To move N disk frm A to C
2)Move n-1 dosk frm A to B this leaves disk N alone on rod A.
3)Move disk N frm A to C.
4)Move n-1 disk frm B to C , so they sit on N.

The concept is that n-1 disk in rod B is considered as a fresh problem and can be solved in the same manner.......................(Recursion-Repetition of some particular steps untill we get the result).

[Disk 1 is moved to rod C if N is odd ,and to Rod 2 if n is even]
www.chessandpoker.com/tower-of-hanoi

TOWER(N,A,B,C)
1) If N=0,then: Return (No disks persent)
2)repeat steps 3 to 5 for K=N,N-1,N-2..........1.
3)Tower function(K-1,A,C,B)
4)Write:A  -> C
5) [Interchange A and B]
Set TEMP:=A,A=B.
    B:=TEMP.
  [End of STEP 2loop]

6)RETURN

0 comments:

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews