Skip to content

Instantly share code, notes, and snippets.

@sunnyc7
Forked from theArjun/README.md
Created January 13, 2019 17:46
Show Gist options
  • Select an option

  • Save sunnyc7/cfad63b18baeb08ce999b8d8223395e5 to your computer and use it in GitHub Desktop.

Select an option

Save sunnyc7/cfad63b18baeb08ce999b8d8223395e5 to your computer and use it in GitHub Desktop.
Tower Of Hanoi by Recursion in Java

Tower of Hanoi

How's it is solved ?

Tower Of Hanoi

Long steps ahead

Steps for Tower Of Hanoi

To know more :

IMAGE ALT TEXT HERE

// TOH refers to Tower Of Hanoi.
public class TOH{
// Defining a method which accepts parameters as: no of disks, name of rods (should match according to name of formal arguments passed).
public void tower(int noOfDisks, String sourceRod, String destinationRod, String auxiliaryRod){
if(noOfDisks == 1){
System.out.format("\nRod %d moved from %s to %s",1,sourceRod,destinationRod);
return ;
}else{
// Key Algorithms :
tower(noOfDisks - 1, "Source Rod","Auxiliary Rod","Destination Rod");
System.out.format("\nDisk %d moved from %s to %s",noOfDisks,sourceRod,destinationRod);
tower(noOfDisks - 1, "Auxiliary Rod","Destination Rod","Source Rod");
}
}
}
// TOHDemo refers to Tower Of Hanoi Demo.
class TOHDemo{
public static void main(String[] args){
// This accepts the no of disks
int noOfDisks = 4;
TOH objectOne = new TOH();
// Passing the no of disks and rod names to recursive function.
objectOne.tower(noOfDisks,"Source Rod","Destination Rod","Auxilary Rod");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment