Hanoi problem

HI!

Is there anyone who can help me with tower of hanoi??


Please!!!!

Comments

  • [b][red]This message was edited by BigQueso at 2004-8-12 3:25:44[/red][/b][hr]
    to understand recursion...one must first understand recursion....


    [code]public class TowersOfHanoi
    {
    private int totalDisks;

    //-----------------------------------------------------------------
    // Sets up the puzzle with the specified number of disks.
    //-----------------------------------------------------------------
    public TowersOfHanoi (int disks)
    {
    totalDisks = disks;
    }

    //-----------------------------------------------------------------
    // Performs the initial call to moveTower to solve the puzzle.
    // Moves the disks from tower 1 to tower 3 using tower 2.
    //-----------------------------------------------------------------
    public void solve ()
    {
    moveTower (totalDisks, 1, 3, 2);
    }

    //-----------------------------------------------------------------
    // Moves the specified number of disks from one tower to another
    // by moving a subtower of n-1 disks out of the way, moving one
    // disk, then moving the subtower back. Base case of 1 disk.
    //-----------------------------------------------------------------
    private void moveTower (int numDisks, int start, int end, int temp)
    {
    if (numDisks == 1)
    moveOneDisk (start, end);
    else
    {
    moveTower (numDisks-1, start, temp, end);
    moveOneDisk (start, end);
    moveTower (numDisks-1, temp, end, start);
    }
    }

    //-----------------------------------------------------------------
    // Prints instructions to move one disk from the specified start
    // tower to the specified end tower.
    //-----------------------------------------------------------------
    private void moveOneDisk (int start, int end)
    {
    System.out.println ("Move one disk from " + start + " to " +
    end);
    }
    }
    [/code]
    this should help.
    good luck.
    BigQ


  • public class TowerMover{

    private static int counter = 0;

    public static void main(String[] argv){
    moveTower(5, 1, 2);
    }

    public static void moveOneDisk(int from, int to){
    System.out.println("Move a disk from " + from + " to " + to + ".");
    counter++;
    System.out.println(counter);
    }

    public static void moveTower(int n, int from, int to){
    if(n == 1){
    moveOneDisk(from, to);
    }
    else{
    int other = 6 - (from + to);
    moveTower(n - 1, from, other);
    moveOneDisk(from, to);
    moveTower(n - 1, other, to);
    }
    }
    }

    here is some more code that is essentially the same as the above
  • This post has been deleted.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories