Monday, January 30, 2017

Recursion Program Java

Tags

Tower of Hanoi: Puzzle in which there are three towers say A,B,C. and some finite number of disks in increasing order of size downwards.

Objective : Move disks from A to C by following below rules:
   1. Only one disk can be moved at a time,and only the top disk.
   2. At no time it is allowed to place a larger disk on small disk.

Following Code Uses Recursion(Function Calling Itself): 

Code::
import java.util.*;
public class Tower 
{  static int c=0;

    public static void main(String[] nt) 
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter Number of Disks: ");
        int n=in.nextInt();
        System.out.println("Moves:");
        hanoi(n,'A','B','C');
        System.out.println("Total Moves: "+c);
    }
    
    public static void hanoi(int n,char A,char B,char C)
    {   if(n<1)
       {
        System.out.println("Please Enter Finite Number of Disks");
        return;
       }
        
        if(n==1)
        {
            System.out.println("From Tower "+A+" to Tower "+C);
            c++;
            return;
        }
        hanoi(n-1,A,C,B);
        System.out.println("From Tower "+A+" to Tower "+C);
        c++;
        hanoi(n-1,B,A,C);   
    }
}

Output::