Skip to content

Instantly share code, notes, and snippets.

@Alxandr
Forked from KaiSforza/Percolation.java
Created August 13, 2012 04:15
Show Gist options
  • Save Alxandr/3336886 to your computer and use it in GitHub Desktop.
Save Alxandr/3336886 to your computer and use it in GitHub Desktop.
class Percolation extends WeightedQuickUnionUF {
private int width;
public Percolation(int n) {
super(n * n + 2);
for(int i = 0; i < n; i++) {
union(1 + n * (n - 1) + i, n * n + 1);
}
width = n;
}
private int position(int i, int j) { // calculates position in 1d array
return 1 + n * i + j;
}
public void open(int i, int j) { // open site (row i, column j) if it is not already
if(i > 0) {
union(position(i-1, j), position(i, j));
} else {
union(position(i-1, j), 0);
}
if(j > 0) {
union(position(i, j-1), position(i, j));
}
if(j < width - 1) {
union(position(i, j+1), position(i, j));
}
}
public boolean isOpen(int i, int j) { // is site (row i, column j) open?
return connected(position(i, j), i > 0 ? position(i-1, j) : 0);
}
public boolean isFull(int i, int j) { // is site (row i, column j) full?
return connected(position(i, j), 0);
}
public boolean percolates() {
return connected(0, width * width + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment