-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathTowerOfHanoi.java
46 lines (42 loc) · 1.38 KB
/
TowerOfHanoi.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.*;
class TowerOfHanoi {
public static void shiftRings(int n, int fromRod, int toRod, int midRod) {
if(n == 1) {
System.out.println("Shifting disk 1 from rod " + fromRod + " to rod " + toRod);
return;
}
shiftRings(n-1, fromRod, midRod, toRod);
System.out.println("Shifting disk " + n + " from rod " + fromRod+ " to rod " + toRod);
shiftRings(n-1, midRod, toRod, fromRod);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rings:");
int n = sc.nextInt();
sc.close();
shiftRings(n, 1, 3, 2);
}
}
/**
* Sample input/output:
* Enter the number of rings:
* 4
* Shifting disk 1 from rod 1 to rod 2
* Shifting disk 2 from rod 1 to rod 3
* Shifting disk 1 from rod 2 to rod 3
* Shifting disk 3 from rod 1 to rod 2
* Shifting disk 1 from rod 3 to rod 1
* Shifting disk 2 from rod 3 to rod 2
* Shifting disk 1 from rod 1 to rod 2
* Shifting disk 4 from rod 1 to rod 3
* Shifting disk 1 from rod 2 to rod 3
* Shifting disk 2 from rod 2 to rod 1
* Shifting disk 1 from rod 3 to rod 1
* Shifting disk 3 from rod 2 to rod 3
* Shifting disk 1 from rod 1 to rod 2
* Shifting disk 2 from rod 1 to rod 3
* Shifting disk 1 from rod 2 to rod 3
*
* Time complexity: O(2^n)
* Space complexity: O(n)
*/