File tree 1 file changed +64
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 5 - Recursion II
1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
3
+ The objective of the puzzle is to move all disks from source rod to destination rod using third rod (say auxiliary). The rules are :
4
+ 1) Only one disk can be moved at a time.
5
+ 2) A disk can be moved only if it is on the top of a rod.
6
+ 3) No disk can be placed on the top of a smaller disk.
7
+ Print the steps required to move n disks from source rod to destination rod.
8
+ Source Rod is named as 'a', auxiliary rod as 'b' and destination rod as 'c'.
9
+
10
+ Input Format :
11
+ Integer n
12
+
13
+ Output Format :
14
+ Steps in different lines (in one line print source and destination rod name separated by space)
15
+
16
+ Constraints :
17
+ 0 <= n <= 20
18
+
19
+ Sample Input 1 :
20
+ 2
21
+ Sample Output 1 :
22
+ a b
23
+ a c
24
+ b c
25
+
26
+ Sample Input 2 :
27
+ 3
28
+ Sample Output 2 :
29
+ a c
30
+ a b
31
+ c b
32
+ a c
33
+ b a
34
+ b c
35
+ a c
36
+ */
37
+
38
+ public class solution {
39
+
40
+ public static void towerOfHanoi(int n, char s, char h, char d) {
41
+ // Write your code here
42
+
43
+ //Base Case
44
+ if (n==1)
45
+ {
46
+ System.out.println(s+" "+d);
47
+ }
48
+ else if (n==0)
49
+ {
50
+ System.out.println("");
51
+ }
52
+ else
53
+ {
54
+ //Move (n-1) disks from source (s) to helper (h) through destination (d)
55
+ towerOfHanoi(n-1,s,d,h);
56
+
57
+ //Move the nth (largest) disk from source (s) to destination (d)
58
+ System.out.println(s+" "+d);
59
+
60
+ //Move the (n-1) disks from helper (h) to destination (d) through source (s)
61
+ towerOfHanoi(n-1,h,s,d);
62
+ }
63
+ }
64
+ }
You can’t perform that action at this time.
0 commit comments