Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Created September 10, 2014 16:59
Show Gist options
  • Save PirosB3/6d21d75ba9b9b04df9aa to your computer and use it in GitHub Desktop.
Save PirosB3/6d21d75ba9b9b04df9aa to your computer and use it in GitHub Desktop.
public class Percolation {
private WeightedQuickUnionUF percolations;
private boolean[] state;
private int width;
public Percolation(int N) {
int total = N * N;
width = N;
percolations = new WeightedQuickUnionUF(total);
state = new boolean[total];
for (int i=0; i < total; i++) {
state[i] = false;
}
}
public Integer[] getNeighbouringAreas(int i, int j) {
Integer top, bottom, left, right;
if ((i - 1) < 0) {
top = null;
} else {
top = getArrayPosition(i-1, j);
}
if ((i + 1) >= width) {
bottom = null;
} else {
bottom = getArrayPosition(i+1, j);
}
if ((j - 1) < 0) {
left = null;
} else {
left = getArrayPosition(i, j-1);
}
if ((j + 1) >= width) {
right = null;
} else {
right = getArrayPosition(i, j+1);
}
return new Integer[]{top, bottom, left, right};
}
private int getArrayPosition(int i, int j) {
return i * width + j;
}
public void open(int i, int j) {
int myPosition = getArrayPosition(i, j);
state[myPosition] = true;
Integer[] allNeighbours = getNeighbouringAreas(i, j);
for (int w = 0; w < allNeighbours.length; w++) {
if ((allNeighbours[w] != null) && (state[allNeighbours[w]] == true)) {
percolations.union(allNeighbours[w], myPosition);
}
}
}
public boolean isOpen(int i, int j) {
return state[getArrayPosition(i, j)];
}
public boolean isFull(int i, int j) {
if (!isOpen(i, j)) return false;
int myPosition = getArrayPosition(i, j);
for (int down=0; down < width; down++) {
if (isOpen(width-1, down) && percolations.connected(myPosition, getArrayPosition(width-1, down))) {
for (int up=0; up < width; up++) {
if (isOpen(0, up) && percolations.connected(myPosition, getArrayPosition(0, up))) {
return true;
}
}
}
}
return false;
}
public boolean percolates() {
for (int i=0; i < width; i++) {
if (isFull(width-1, i)) {
return true;
}
}
return false;
}
/*public static void main(String[] args) {
Percolation p = new Percolation(4);
p.open(0, 0);
p.open(0, 1);
p.open(0, 2);
//p.open(1, 2);
p.open(2, 3);
if (p.percolates()) {
System.out.println("WOOHOO!");
}
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment