Skip to content

Commit 2a20ec0

Browse files
authored
Add Java Implementation
1 parent 305e48d commit 2a20ec0

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Math/TowerofHanoi/toh.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

0 commit comments

Comments
 (0)