Skip to content

Commit 4a13638

Browse files
Merge pull request #242 from saggu10417/master
Tower of Hanoi
2 parents c12243c + ba27f7f commit 4a13638

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

Tower Of Hanoi/TOH.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// C++ recursive function to
2+
// solve tower of hanoi puzzle
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
void towerOfHanoi(int n, char from_rod,
7+
char to_rod, char aux_rod)
8+
{
9+
if (n == 1)
10+
{
11+
cout << "Move disk 1 from rod " << from_rod <<
12+
" to rod " << to_rod<<endl;
13+
return;
14+
}
15+
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
16+
cout << "Move disk " << n << " from rod " << from_rod <<
17+
" to rod " << to_rod << endl;
18+
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
19+
}
20+
21+
// Driver code
22+
int main()
23+
{
24+
int n = 4; // Number of disks
25+
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
26+
return 0;
27+
}
28+
29+
// This is code is contributed by rathbhupendra
30+

Tower Of Hanoi/TOH.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Java recursive program to solve tower of hanoi puzzle
2+
3+
class GFG
4+
{
5+
// Java recursive function to solve tower of hanoi puzzle
6+
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
7+
{
8+
if (n == 1)
9+
{
10+
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
11+
return;
12+
}
13+
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
14+
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
15+
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
16+
}
17+
18+
// Driver method
19+
public static void main(String args[])
20+
{
21+
int n = 4; // Number of disks
22+
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
23+
}
24+
}
25+

Tower Of Hanoi/TOH.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Recursive Python function to solve tower of hanoi
2+
3+
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
4+
if n == 1:
5+
print "Move disk 1 from rod",from_rod,"to rod",to_rod
6+
return
7+
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
8+
print "Move disk",n,"from rod",from_rod,"to rod",to_rod
9+
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
10+
11+
# Driver code
12+
n = 4
13+
TowerOfHanoi(n, 'A', 'C', 'B')
14+
# A, C, B are the name of rods
15+
16+
# Contributed By Harshit Agrawal
17+

0 commit comments

Comments
 (0)