/* vim: set expandtab tabstop=4 shiftwidth=4 : */ public class Percolation { private int N; private boolean[] opened; private WeightedQuickUnionUF uf; // create N-by-N grid, with all sites blocked public Percolation(int N) { this.N = N; int n = (N*N)+2; uf = new WeightedQuickUnionUF(n); opened = new boolean[n]; opened[0] = true; opened[n-1] = true; } // open site (row i, column j) if it is not already public void open(int i, int j) { if (i < 1 || j < 1 || i > N || j > N) throw new java.lang.IndexOutOfBoundsException("check your indexes"); int x = (j-1)*N+i; if (opened[x]) return; opened[x] = true; if (i > 1 && opened[x-1]) uf.union(x, x-1); if (i < N && opened[x+1]) uf.union(x, x+1); if (j == 1) { uf.union(x, 0); if (opened[x+N]) uf.union(x, x+N); } else if (j == N) { uf.union(x, N*N+1); if (opened[x-N]) uf.union(x, x-N); } else { if (opened[x-N]) uf.union(x, x-N); if (opened[x+N]) uf.union(x, x+N); } } // is site (row i, column j) open? public boolean isOpen(int i, int j) { if (i < 1 || j < 1 || i > N || j > N) throw new java.lang.IndexOutOfBoundsException("check your indexes"); return opened[(j-1)*N+i]; } // is site (row i, column j) full? public boolean isFull(int i, int j) { if (i < 1 || j < 1 || i > N || j > N) throw new java.lang.IndexOutOfBoundsException("check your indexes"); int x = (j-1)*N+i; return ((opened[x]) && (uf.find(x) == 0)); } // does the system percolate? public boolean percolates() { return (uf.find(0) == uf.find(N*N+1)); } }