Friday, January 28, 2011

Hanoi Towers - C#

Here I'll show you the issue of Towers of Hanoi code .. Using a recursive way:

namespace HanoiTowers
{
    class Program
    {
        static void Main(string[] args)
        {
            int n;

            do{
                Console.WriteLine("Enter number: ");
                n = Int32.Parse(Console.ReadLine());
            }while(n<=0);

            Hanoi(n, 'A', 'B', 'C');
            Console.ReadLine();
        }

        static void Hanoi(int n, char A, char B, char C)
        {
            if (n == 1)
                Console.WriteLine("{0} --> {1}", A, C);
            else
            {
                Hanoi(n - 1, A, C, B);
                Console.WriteLine("{0} --> {1}", A, C);
                Hanoi(n - 1, B, A, C);
            }
        }
    }
}

This picture shows the method of work on this issue:

Hanoi Towers

2 comments:

  1. yes !! good algorithm
    thanks man

    ReplyDelete
  2. Hi,

    Nice article!

    I saw this example of towers of Hanoi done in windows forms, using the same algorithm.

    Have a look:

    http://www.codeproject.com/Articles/393158/Towers-of-Hanoi

    ReplyDelete