Skip to main content

Posts

Showing posts with the label recursion

Towers of Hanoi

Towers of Hanoi is a popular mathematical puzzle invented in 1883 by French mathematician Eduoardo Lucas. It is also a popular example in coding world because it is a typical example where a recursive solution is much easier than iterative solution. In the puzzle, there are 3 rods and n discs of different sizes. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. Gif file from wikipedia Aim of the game is to transfer these  n discs to the 3rd rod, using 2nd rod as temporary location, but keeping in mind that only one disc can be moved at a time. a larger disc can not be placed above a smaller disc. How do we solve this puzzle? If some how we move n-1 discs to 2nd rod in correct order, we only have largest disc in 1st rod. And it can be moved to 3rd rod. So now we need to find a method of moving n-1 discs from 1st rod to 2nd rod in correct order. Again we can use 3rd rod for intermediate stora...