ISourceCode

Make the frequent cases fast and the rare case correct

Towers of Hanoi – Recursion at Work

class TowerHanoi
{
        static int Disks = 3;
        public static void main(String[] args)
        {
                Hanoi(Disks, 'A', 'B', 'C');
        }

        public static void Hanoi(int top,char source, char temp, char dest)
        {
                if(top==1)
                        System.out.println("Disk 1 from " + source + " to "+ dest);
                else
                {
                        Hanoi(top-1, source, dest, temp); 
                        System.out.println("Disk " + top +" from " + source + " to "+ dest);
                        Hanoi(top-1, temp, source, dest); 
                }
        }       
}

OUTPUT:

~$ java TowerHanoi
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: