Skip to content

Commit 17c3b2d

Browse files
feat(recursion-solutions): implement tower of hanoi using recursion
1 parent 57fb070 commit 17c3b2d

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
PROBLEM:
3+
Move N disks from source to destination using helper.
4+
5+
APPROACH:
6+
- Move n-1 disks to helper
7+
- Move nth disk to destination
8+
- Move n-1 from helper to destination
9+
*/
10+
11+
public class TowerOfHanoi {
12+
13+
public static void solve(int n, String src, String helper, String dest) {
14+
if (n == 1) {
15+
System.out.println("Move disk 1 from " + src + " to " + dest);
16+
return;
17+
}
18+
19+
solve(n - 1, src, dest, helper);
20+
21+
System.out.println("Move disk " + n + " from " + src + " to " + dest);
22+
23+
solve(n - 1, helper, src, dest);
24+
}
25+
26+
public static void main(String[] args) {
27+
solve(3, "A", "B", "C");
28+
}
29+
}

0 commit comments

Comments
 (0)