televisiongugl.blogg.se

Hanoi towers 4 pegs
Hanoi towers 4 pegs




  • Move the last disk (the largest) from peg 1 to peg 3.
  • Move n - 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
  • Moving n disks can be viewed in terms of moving only n - 1 disks (hence the recursion) as follows: Instead, attacking this problem with recursion in mind allows the steps to be simple. If we were to approach this problem with conventional methods, we would rapidly find ourselves hopelessly knotted up in managing the disks. We wish to develop an algorithm that prints the precise sequence of peg-to-peg disk transfers. Let us assume that the priests are attempting to move the disks from peg 1 to peg 3. Towers of Hanoi for the case with four disks. Supposedly, the world will end when the priests complete their task, so there is little incentive for us to facilitate their efforts.įigure 15.14. Three pegs are provided, one being used for temporarily holding disks. The priests are attempting to move the stack from one peg to another under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. The initial stack has 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. Legend has it that in a temple in the Far East, priests are attempting to move a stack of golden disks from one diamond peg to another (Fig. The Towers of Hanoi is one of the most famous classic problems every budding computer scientist must grapple with. In this section, we present a problem whose recursive solution demonstrates the elegance of recursion, and whose iterative solution may not be as apparent.

    hanoi towers 4 pegs hanoi towers 4 pegs

    In the preceding sections of this chapter, we studied methods that can be easily implemented both recursively and iteratively.






    Hanoi towers 4 pegs