-
Notifications
You must be signed in to change notification settings - Fork 0
/
Percolation.java
92 lines (76 loc) · 2.7 KB
/
Percolation.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.Set;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
private WeightedQuickUnionUF model;
private int n;
private int top;
private int bottom;
private Set<Integer> opened;
// creates n-by-n grid, with all sites initially blocked
public Percolation(int n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be a positive integer");
}
this.n = n;
this.top = 0;
this.bottom = n + 1;
model = new WeightedQuickUnionUF(n + 2);
opened = new Set<Integer>();
// connect top row to top
for (int i = 1; i < Math.sqrt(n); i++) {
this.model.union(this.top, i);
}
// connect bottom row to bottom
for (int i = n; i > n - Math.sqrt(n); i--) {
this.model.union(this.bottom, i);
}
}
private int convertToId(int row, int col) {
if (row < 1 || col < 1 || row > this.n || col > this.n) {
throw new IllegalArgumentException("Row or Col index is out of bounds");
}
return (int) (Math.sqrt(this.n) * (row - 1)) + col;
}
// opens the site (row, col) if it is not open already
public void open(int row, int col) {
int id = convertToId(row, col);
<