Thursday, April 14, 2011

Tower of Hanoi Solution


import java.util.Scanner;
public class HanoiTowerSoln
{
    static void MoveDisc(int whichdisc,char frompeg,char topeg)
    {
        System.out.println("Move ring " + whichdisc + " from " + frompeg + " to " + topeg);
    }
    static void MoveTower(int height,char frompeg,char topeg,char usingpeg)
    {
        if(height>0)
        {
            MoveTower(height-1,frompeg,usingpeg,topeg);
            MoveDisc(height,frompeg,topeg);
            MoveTower(height-1,usingpeg,topeg,frompeg);
        }
    }

    public static void main(String[] args)
    {

        int n;
        Scanner in=new Scanner(System.in);
        long t1,t2;
        System.out.println("Enter number of rings please");
        n=in.nextInt();
        t1=System.currentTimeMillis();
        MoveTower(n,'A','C','B');
        t2=System.currentTimeMillis();
        System.out.println("\n\nTime Taken = " + (t2-t1));
    }
}