Last active
August 29, 2015 14:15
-
-
Save gcandal/c34a6739a9b75274aad3 to your computer and use it in GitHub Desktop.
Percolation Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Percolation { | |
private WeightedQuickUnionUF unionUF, unionUFPerc; | |
private int N; | |
private boolean[][] open; | |
// create N-by-N grid, with all sites blocked | |
public Percolation(int N) | |
{ | |
if (N <= 0) | |
throw new IllegalArgumentException(); | |
this.unionUF = new WeightedQuickUnionUF(N*N + 1); | |
this.unionUFPerc = new WeightedQuickUnionUF(N*N + 2); | |
open = new boolean[N][N]; | |
this.N = N; | |
} | |
private int twoDtoOneD(int row, int column) { | |
return N*(row-1) + column - 1; | |
} | |
private void checkBounds(int i, int j) { | |
if (i < 1 || i > N || j < 1 || j > N) | |
throw new IndexOutOfBoundsException(); | |
} | |
private void doubleUnion(int id1, int id2) { | |
unionUF.union(id1, id2); | |
unionUFPerc.union(id1, id2); | |
} | |
// open site (row i, column j) if it is not already | |
public void open(int i, int j) | |
{ | |
checkBounds(i, j); | |
if (open[i - 1][j - 1]) | |
return; | |
open[i - 1][j - 1] = true; | |
if (i == 1) | |
doubleUnion(twoDtoOneD(i, j), N*N); | |
if (i == N) | |
unionUFPerc.union(twoDtoOneD(i, j), N*N + 1); | |
if (i > 1 && open[i - 2][j - 1]) | |
doubleUnion(twoDtoOneD(i, j), twoDtoOneD(i - 1, j)); | |
if (i < N && open[i][j - 1]) | |
doubleUnion(twoDtoOneD(i, j), twoDtoOneD(i + 1, j)); | |
if (j > 1 && open[i - 1][j - 2]) | |
doubleUnion(twoDtoOneD(i, j), twoDtoOneD(i, j - 1)); | |
if (j < N && open[i - 1][j]) | |
doubleUnion(twoDtoOneD(i, j), twoDtoOneD(i, j + 1)); | |
} | |
// is site (row i, column j) open? | |
public boolean isOpen(int i, int j) | |
{ | |
checkBounds(i, j); | |
return open[i - 1][j - 1]; | |
} | |
// is site (row i, column j) full? | |
public boolean isFull(int i, int j) | |
{ | |
checkBounds(i, j); | |
return unionUF.connected(twoDtoOneD(i, j), N*N); | |
} | |
// does the system percolate? | |
public boolean percolates() | |
{ | |
return unionUFPerc.connected(N*N, N*N + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment