// solve tower of hanoi puzzle using namespace std; void towerOfHanoi( int n, char from_rod, { { ' to rod ' << to_rod<<endl; } cout << 'Move disk ' << n << ' from rod ' << from_rod << towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); int main() int n = 4; // Number of disks towerOfHanoi(n, 'A' , 'C' , 'B' ); // A, B and C are names of rods } // This is code is contributed by rathbhupendra |
// C recursive function to solve tower of hanoi puzzle void towerOfHanoi( int n, char from_rod, char to_rod, char aux_rod) if (n 1) printf ( 'n Move disk 1 from rod %c to rod %c' , from_rod, to_rod); } printf ( 'n Move disk %d from rod %c to rod %c' , n, from_rod, to_rod); } int main() int n = 4; // Number of disks towerOfHanoi(n, 'A' , 'C' , 'B' ); // A, B and C are names of rods } |
// Java recursive program to solve tower of hanoi puzzle class GFG // Java recursive function to solve tower of hanoi puzzle static void towerOfHanoi( int n, char from_rod, char to_rod, char aux_rod) if (n 1 ) System.out.println( 'Move disk 1 from rod ' + from_rod + ' to rod ' + to_rod); } System.out.println( 'Move disk ' + n + ' from rod ' + from_rod + ' to rod ' + to_rod); } // Driver method { towerOfHanoi(n, 'A' , 'C' , 'B' ); // A, B and C are names of rods } |
# Recursive Python function to solve tower of hanoi def TowerOfHanoi(n , from_rod, to_rod, aux_rod): print 'Move disk 1 from rod' ,from_rod, 'to rod' ,to_rod TowerOfHanoi(n - 1 , from_rod, aux_rod, to_rod) print 'Move disk' ,n, 'from rod' ,from_rod, 'to rod' ,to_rod n = 4 # A, C, B are the name of rods # Contributed By Harshit Agrawal |
// tower of hanoi puzzle { // C# recursive function to solve static void towerOfHanoi( int n, char from_rod, { { Console.WriteLine( 'Move disk 1 from rod ' + from_rod return ; towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + from_rod + ' to rod ' + to_rod); } // Driver method { int n = 4; // A, B and C are names of rods } |
//PHP code to solve Tower of Hanoi problem. // Recursive Function to solve Tower of Hanoi function towerOfHanoi( $n , $from_rod , $to_rod , $aux_rod ) { if ( $n 1) { echo ( 'Move disk 1 from rod $from_rod to rod $to_rod n' ); } towerOfHanoi( $n -1, $from_rod , $aux_rod , $to_rod ); echo ( 'Move disk $n from rod $from_rod to rod $to_rod n' ); towerOfHanoi( $n -1, $aux_rod , $to_rod , $from_rod ); } // Driver code // number of disks towerOfHanoi( $n , 'A' , 'C' , 'B' ); // This code is contributed by akash7981 |