Created
March 29, 2018 03:43
-
-
Save computingfreak/20fc1e92078a2683c5344ba7b1c17b76 to your computer and use it in GitHub Desktop.
Towers Of Hanoi Recursive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. | |
* It consists of three rods, and a number of disks of different sizes which can slide onto any rod. | |
* The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, | |
* thus making a conical section. | |
* The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: | |
* Only one disk may be moved at a time. | |
* Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, | |
* on top of the other disks that may already be present on that rod. | |
* No disk may be placed on top of a smaller disk.**/ | |
import java.io.*; | |
public class TowersOfHanoiRecursive | |
{ | |
static int flag; | |
public static void main()throws IOException | |
{ | |
TowersOfHanoiRecursive obj=new TowersOfHanoiRecursive(); | |
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); | |
System.out.println("Enter number of rings"); | |
int N=Integer.parseInt(br.readLine()); | |
flag=0; | |
obj.recmove('A','B','C',N); | |
System.out.println("No. of Moves ---> "+flag);//Moves((2^N)-1) | |
flag=0; | |
obj.Towers(N,'A','B','C'); | |
System.out.println("No. of Moves ---> "+flag);//Moves((2^N)-1) | |
} | |
/** | |
* Recursively Move n-1 disks to get largest n then move back n-1 disks in place to get disks in order. | |
* Recursive function terminates when stack of small disks is reduced to 1 disk.. i.e n=1. | |
*/ | |
/** Moves N Discs from A to C */ | |
void recmove(char a,char b,char c,int n) | |
{ | |
if(n==0) | |
System.out.println("WRONG INPUT !!!"); | |
if(n==1) | |
{ | |
System.out.println("Move from "+a+" to "+c); | |
flag++; | |
} | |
if(n>1) | |
{ | |
recmove(a,c,b,n-1); | |
recmove(a,b,c,1); | |
recmove(b,a,c,n-1); | |
} | |
} | |
/** Moves N Discs from A to B */ | |
public static void Towers(int numDisks,char src, char dest, char temp) | |
{ | |
if (numDisks == 1) | |
{ | |
flag++; | |
System.out.println("Move top disk from pole "+src+" to pole "+dest); | |
} | |
else | |
{ | |
Towers(numDisks-1,src,temp,dest); | |
Towers(1,src,dest,temp); | |
Towers(numDisks-1,temp,dest,src); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment