| 10 | import edu.princeton.cs.algs4.WeightedQuickUnionUF; |
| 11 | |
| 12 | public class Percolation { |
| 13 | private static int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } }; |
| 14 | private WeightedQuickUnionUF uf1; // for full |
| 15 | private WeightedQuickUnionUF uf2; // for percolate |
| 16 | private boolean[] sites; |
| 17 | private int gridSize; |
| 18 | private int numOfOpenSites; |
| 19 | |
| 20 | // creates n-by-n grid, with all sites initially blocked |
| 21 | public Percolation(int n) { |
| 22 | if (n <= 0) throw new IllegalArgumentException("n should be larger than 0"); |
| 23 | gridSize = n; |
| 24 | uf1 = new WeightedQuickUnionUF(n * n + 1); |
| 25 | uf2 = new WeightedQuickUnionUF(n * n + 2); |
| 26 | sites = new boolean[n * n + 2]; |
| 27 | sites[0] = true; // uf1's top and uf2's top |
| 28 | sites[n * n + 1] = true; // uf2's bottom |
| 29 | numOfOpenSites = 0; |
| 30 | } |
| 31 | |
| 32 | // calculate index for row col |
| 33 | private int getSite(int row, int col) { |
| 34 | if (row == 0) return 0; |
| 35 | if (row == gridSize + 1) col = 1; |
| 36 | return (row - 1) * gridSize + col; |
| 37 | } |
| 38 | |
| 39 | private void validate(int p, String desc) { |
| 40 | if (p < 1 || p > gridSize) |
| 41 | throw new IllegalArgumentException(desc + " index i out of bounds"); |
| 42 | } |
| 43 | |
| 44 | private boolean isInGrid(int row, int col) { |
| 45 | return row >= 1 && row <= gridSize && col >= 1 && col <= gridSize; |
| 46 | } |
| 47 | |
| 48 | // opens the site (row, col) if it is not open already |
| 49 | public void open(int row, int col) { |
| 50 | validate(row, "row"); |
| 51 | validate(col, "col"); |
| 52 | if (!isOpen(row, col)) { |
| 53 | numOfOpenSites++; |
| 54 | sites[getSite(row, col)] = true; |
| 55 | for (int i = 0; i < dirs.length; i++) { |
| 56 | int neightborRow = row + dirs[i][0]; |
| 57 | int neightborCol = col + dirs[i][1]; |
| 58 | if (neightborRow == gridSize + 1) |
| 59 | uf2.union(getSite(neightborRow, neightborCol), getSite(row, col)); |
| 60 | if (neightborRow == 0 || isInGrid(neightborRow, neightborCol) && isOpen( |
| 61 | neightborRow, neightborCol)) { |
| 62 | uf1.union(getSite(neightborRow, neightborCol), getSite(row, col)); |
| 63 | uf2.union(getSite(neightborRow, neightborCol), getSite(row, col)); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // is the site (row, col) open? |
nothing calls this directly
no outgoing calls
no test coverage detected