-
-
Save Alxandr/3336886 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
class Percolation extends WeightedQuickUnionUF { | |
private int width; | |
public Percolation(int n) { | |
super(n * n + 2); | |
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