To know more :
-
-
Save sunnyc7/cfad63b18baeb08ce999b8d8223395e5 to your computer and use it in GitHub Desktop.
Tower Of Hanoi by Recursion in Java
This file contains hidden or 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
| // 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"); | |
| } | |
| } | |
| } |
This file contains hidden or 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
| // 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


