-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolation.java
More file actions
76 lines (65 loc) · 2.4 KB
/
Percolation.java
File metadata and controls
76 lines (65 loc) · 2.4 KB
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
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
private final int[][] grid;
private final WeightedQuickUnionUF quickUnionUF;
private final int virtualTopSite;
private final int virtualBottomSite;
private int count;
public Percolation(int n) {
virtualBottomSite = n * n + 1;
virtualTopSite = 0;
quickUnionUF = new WeightedQuickUnionUF(n * n + 2);
grid = new int[n][n];
}
public int to1D(int row, int col) {
return (row * grid.length + col) + 1;
}
public void open(int row, int col) {
--row;
--col;
if (row >= grid.length || col >= grid.length || row < 0 || col < 0) {
throw new IllegalArgumentException();
}
else {
if (!isOpen(row, col)) {
grid[row][col] = 1;
++count;
if (row == 0) {
quickUnionUF.union(virtualTopSite, to1D(row, col));
}
if (row == grid.length - 1) {
quickUnionUF.union(virtualBottomSite, to1D(row, col));
}
}
if (row - 1 >= 0 && isOpen(row - 1, col)) {
quickUnionUF.union(to1D(row, col), to1D(row - 1, col));
}
if (row + 1 < grid.length && isOpen(row + 1, col)) {
quickUnionUF.union(to1D(row, col), to1D(row + 1, col));
}
if (col + 1 < grid.length && isOpen(row, col + 1)) {
quickUnionUF.union(to1D(row, col), to1D(row, col + 1));
}
if (col - 1 >= 0 && isOpen(row, col - 1)) {
quickUnionUF.union(to1D(row, col), to1D(row, col - 1));
}
}
}
public boolean isOpen(int row, int col) {
return grid[row][col] == 1;
}
public boolean isFull(int row, int col) {
--row;
--col;
if (row >= grid.length || col >= grid.length || row < 0 || col < 0)
throw new IllegalArgumentException();
return quickUnionUF.find(to1D(row,col)) == quickUnionUF.find(virtualTopSite)
&& isOpen(row,col);
}
public int numberOfOpenSites() {
return count;
}
public boolean percolates() {
return (quickUnionUF.find(virtualTopSite) == quickUnionUF.find(virtualBottomSite));
}
}