Created
September 10, 2014 17:32
-
-
Save PirosB3/edc3d937640c2ccfbf3c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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; | |
} | |
} | |
private void validateInput(int i, int j) { | |
if (i <= 0 || i > width) { | |
throw new IndexOutOfBoundsException("row index i out of bounds"); | |
} | |
if (j <= 0 || j > width) { | |
throw new IndexOutOfBoundsException("row index i out of bounds"); | |
} | |
} | |
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-1) * width + (j-1); | |
} | |
public void open(int i, int j) { | |
validateInput(i, 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) { | |
validateInput(i, j); | |
return state[getArrayPosition(i, j)]; | |
} | |
public boolean isFull(int i, int j) { | |
validateInput(i, j); | |
if (!isOpen(i, j)) return false; | |
int myPosition = getArrayPosition(i, j); | |
for (int down=0; down < width; down++) { | |
if (isOpen(width, down+1) && percolations.connected(myPosition, getArrayPosition(width, down+1))) { | |
for (int up=0; up < width; up++) { | |
if (isOpen(1, up+1) && percolations.connected(myPosition, getArrayPosition(1, up+1))) { | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} | |
public boolean percolates() { | |
for (int i=0; i < width; i++) { | |
if (isFull(width, i+1)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment