


This approach can be given a rigorous mathematical formalism with the theory of dynamic programming,and is often used as an example of recursion when teaching programming. This step, moving a single disc from peg A to peg B, is trivial. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. The above is a recursive algorithm: to carry out steps 1 and 3, apply the same algorithm again for n−1. Move n−1 discs from B to C so they sit on disc n Number the discs from 1 (smallest, topmost) to n (largest, bottommost) Label the pegs A, B, C-these labels may move at different steps The following procedure demonstrates this approach. Move(n,”source tower”,”intermediate tower”,”destination tower”) Ī key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached.

move n-1 disks from source to intermediate tower > Works in Microsoft VC++ 6.0, windows xp. Then move disk 2 from peg A to peg B and, finally, move disk 1 from peg C to peg B. The target is to move both these disks to peg B. Take an example with 2 disks: Disk 1 on top of Disk 2 at peg A. > This C++ program is to solve the towers of hanoi problem. Let’s try to solve a puzzle Tower of Hanoi using recursion.
