Recursive program on Tower of Hanoi

Recursive program on Tower of Hanoi.
import java.util.*;
class TowerHRec
{
    public static void main(String args[])
    {
        int n;
        char beg='A',aux='B',end='C';
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter number of disks:");
        n=sc.nextInt();
        TowerHRec obj=new TowerHRec();
        obj.move(n,beg,aux,end);
    }
    void move(int n,char beg,char aux,char end)
    {
        if(n==1)
          System.out.println("Move "+n+" disks from "+beg+" -> "+end);
         
        else
        {
            move(n-1,beg,end,aux);
            System.out.println("Move "+n+" disks from "+beg+" -> "+end);
            move(n-1,aux,beg,end);
        }
    }
}
       
OUTPUT---
Enter number of disks:
4
Move 1 disks from A -> B
Move 2 disks from A -> C
Move 1 disks from B -> C
Move 3 disks from A -> B
Move 1 disks from C -> A
Move 2 disks from C -> B
Move 1 disks from A -> B
Move 4 disks from A -> C
Move 1 disks from B -> C
Move 2 disks from B -> A
Move 1 disks from C -> A
Move 3 disks from B -> C
Move 1 disks from A -> B
Move 2 disks from A -> C
Move 1 disks from B -> C

Comments

Popular posts from this blog

Sort Boundary Elements Of A Matrix

Lucky Number In Java ISC

Program to fill a square matrix of size ‘n*n” in a circular fashion (clockwise) with natural numbers from 1 to n*n, taking ‘n’ as input.