Main Menu

Deitel Exersices
Downloads
Contact ME


 


Back


Links
CE Main Site
Sharif University
Wikipedia
2Del
PHP
Javascript





    

In the name of GOD


Deitel Exercise : 3.42

(Towers of Hanoi) ... (avvalesh y 'aalame mozakhrafat dare) ... We wish to develop an algorithm that prints the percise sequence of peg-to-peg disk transfers.
If we were to approach this problem with conventional methods, wo would rapidly find ourselves hopelessly knotted up in managing the disks. Instead, if we attack the problem with recursion in mind, i immediately becomes tracable. Moving n disks can be viewed in terms of moving only n-1 disks (hence, recursion),, as follows:


     a) Move n-1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
     b) Move the last disk (the largest) from peg 1 to peg 3.
     c) Move the n-1 disks from peg 2 to peg 3, using peg 1 as a temorary holding area.


The process ends when the last task involves moving n=1 disk, i.e. the base case. This is accomplished by trivially moving the disk without the need for a teomporary holding area. Write a problem to solve the Towers of Hanoi problem. Use a recursive function with four parameters:


     a) The number of disks to be moved
     b) The peg on which these disks are initially threaded
     c) The peg to which this stack of disks is to be moved
     d) The peg to be used as a temporary holding area


Your program should print percise instructions it will take to move the disk from the starting peg to the destination peg. For example, to move a stack of three disks from peg 1 to peg 3 , your program should print the following series of moves:


     1 -> 3 (This means move one disk from peg 1 to peg 3.)
     1 -> 2
     3 -> 2
     1 -> 3
     2 -> 1
     2 -> 3
     1 -> 3