Skip to content

Commit da11970

Browse files
committed
solve tower of Hanoi problem recursively
1 parent 22742a9 commit da11970

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package Lecture12;
2+
3+
public class TowerOfHanoi {
4+
5+
public static void main(String[] main) {
6+
7+
int N = 3;
8+
TOH(N, "SOURCE", "DESTINATION", "HELPER");
9+
}
10+
11+
public static void TOH(int n, String source, String destination,
12+
String helper) {
13+
14+
if (n == 0) {
15+
return;
16+
}
17+
TOH(n - 1, source, helper, destination);
18+
19+
System.out.println("Move " + n + " th disk from " + source + " to "
20+
+ destination);
21+
22+
TOH(n - 1, helper, destination, source);
23+
}
24+
}
25+
26+
/*
27+
output:
28+
Move 1 th disk from SOURCE to DESTINATION
29+
Move 2 th disk from SOURCE to HELPER
30+
Move 1 th disk from DESTINATION to HELPER
31+
Move 3 th disk from SOURCE to DESTINATION
32+
Move 1 th disk from HELPER to SOURCE
33+
Move 2 th disk from HELPER to DESTINATION
34+
Move 1 th disk from SOURCE to DESTINATION
35+
*/

0 commit comments

Comments
 (0)