-
Notifications
You must be signed in to change notification settings - Fork 0
/
TowerOfHanoi.java
65 lines (49 loc) · 994 Bytes
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.*;
import java.io.*;
class Tower
{
private Stack<Integer> disks;
private int index;
public Tower(int i)
{
index = i;
disks = new ArrayList<Integer>();
}
public addDisks(int disk)
{
if (this.disks.top >= disk)
{
System.out.println("Disk in in-appropriate place");
return;
}
this.disks.push(i);
}
public removeDisk(int disk)
{
this.disks.pop();
}
public void moveDisks(int n, Tower source, Tower destination, Tower buffer)
{
if (n <= 0)
return;
moveDisks(n - 1, source, buffer, destination);
System.out.println("Moving disk " + n + " from " + source + " to " + destination);
moveDisks(n - 1, buffer, destination, source);
}
}
public class TowerOfHanoi
{
public static void main(String args[])
{
Tower[] towers = new Tower[3];
for (int i = 0; i < 3; i ++)
{
towers[i] = new Tower(i);
}
for(int i = 3; i > 0; i --)
{
towers[0].disks.push(i);
}
moveDisks(3, towers[0], towers[1], towers[2]);
}
}