Skip to content

Instantly share code, notes, and snippets.

@KaiSforza
Forked from Alxandr/Percolation.java
Created August 13, 2012 05:16
Show Gist options
  • Select an option

  • Save KaiSforza/3337137 to your computer and use it in GitHub Desktop.

Select an option

Save KaiSforza/3337137 to your computer and use it in GitHub Desktop.
public class Percolation {
private int width;
private int count;
private int[] sz;
private int[] id;
//imported
// Return the number of disjoint sets.
public int count() {
return count;
}
// Return component identifier for component containing p
public int find(int p) {
while (p != id[p])
p = id[p];
return p;
}
// Are objects p and q in the same set?
public boolean connected(int p, int q) {
return find(p) == find(q);
}
// Replace sets containing p and q with their union.
public void union(int p, int q) {
int i = find(p);
int j = find(q);
if (i == j) return;
// make smaller root point to larger one
if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
else { id[j] = i; sz[i] += sz[j]; }
count--;
}
public Percolation(int n) {
count = n*n + 2;
id = new int[n*n +2];
sz = new int[n*n + 2];
for (int i = 0; i < n*n + 2; i++) {
id[i] = i;
sz[i] = 1;
}
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