Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Towers of Hanoi problem in C#

 The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods(towers), and a number of disks of different sizes which can slide onto any rod. 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.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the towers and placing it on top of another tower i.e. a disk can only be moved if it is the uppermost disk on a tower.
  • No disk may be placed on top of a smaller disk.

public class TowersOfHanoi
{
    public static void Main(String[] args)
    {
        char startPeg = 'A'; // start tower in output
        char endPeg = 'C'; // end tower in output
        char tempPeg = 'B'; // temporary tower in output
        int totalDisks = 3; // number of disks

        solveTowers(totalDisks, startPeg, endPeg, tempPeg);
    }

    private static void solveTowers(int n, char startPeg, char endPeg, char tempPeg)
    {
        if (n > 0)
        {
            solveTowers(n - 1, startPeg, tempPeg, endPeg);
            Console.WriteLine("Move disk from " + startPeg + ' ' + endPeg);
            solveTowers(n - 1, tempPeg, endPeg, startPeg);

        }
    }        

}


Output

Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

---------------------------

Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now