Skip to content

Commit 4eab717

Browse files
Nikhilesh SatishNikhilesh Satish
authored andcommitted
Added Tower of Hanoi code using recursion and a sample test
1 parent 4c70c4d commit 4eab717

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

src/main/java/com/thealgorithms/recursion/TowerOfHanoi.java

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,13 @@
44

55
public class TowerOfHanoi {
66

7-
public void solveHanoi(int n,char src,char dest,char aux)
8-
{
9-
if(n==1)
10-
{
11-
System.out.println("Move disk 1 from "+src+" to "+dest);
7+
public static void solveHanoi(int n, char src, char dest, char aux) {
8+
if (n == 1) {
9+
System.out.println("Move disk 1 from " + src + " to " + dest);
1210
return;
1311
}
14-
solveHanoi(n-1,src,aux,dest);
15-
System.out.println("Move disk "+n+" from "+src+" to "+dest);
16-
solveHanoi(n-1,aux,dest,src);
17-
12+
solveHanoi(n - 1, src, aux, dest);
13+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
14+
solveHanoi(n - 1, aux, dest, src);
1815
}
19-
2016
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.thealgorithms.recursion;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
class TowerOfHanoiTest {
6+
7+
@Test
8+
void testSolve() {
9+
TowerOfHanoi.solveHanoi(3, 'A', 'B', 'C');
10+
}
11+
}

0 commit comments

Comments
 (0)