Skip to content

Instantly share code, notes, and snippets.

@theArjun
Last active January 20, 2019 15:13
Show Gist options
  • Select an option

  • Save theArjun/81b44108fa80cd05a11de9f92e7ee408 to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/81b44108fa80cd05a11de9f92e7ee408 to your computer and use it in GitHub Desktop.
Tower Of Hanoi by Recursion

Tower of Hanoi

How's it is solved ?

Tower Of Hanoi

Long steps ahead, but you're too intelligent to understand

Steps for Tower Of Hanoi

To know more :

IMAGE ALT TEXT HERE

// TOH refers to Tower of Hanoi.
#include<stdio.h>
using namespace std;
// Defining a void method which accepts parameters as: no of disks, name of rods (should match according to name of formal arguments passed).
void tower(int noOfDisks, const char* sourceRod, const char* destinationRod, const char* auxiliaryRod){
if(noOfDisks == 1){
printf("\nDisk %d moved from %s to %s",1,sourceRod,destinationRod);
return ;
}else{
// Key Algorithms :
tower(noOfDisks - 1, "Source Rod","Auxiliary Rod","Destination Rod");
printf("\nDisk %d moved from %s to %s",noOfDisks,sourceRod,destinationRod);
tower(noOfDisks - 1, "Auxiliary Rod","Destination Rod","Source Rod");
}
}
int main(){
// This accepts the no of disks
int noOfDisks= 4;
// Passing the no of disks and rod names to recursive function.
tower(noOfDisks,"Source Rod","Destination Rod","Auxilary Rod");
return 0;
}
// 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");
}
}
@parajuliamit
Copy link
Copy Markdown

Thank You, Sir!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment