1+ import edu .princeton .cs .algs4 .WeightedQuickUnionUF ;
2+
3+ public class Percolation {
4+
5+ private boolean [][] grid ;
6+ private int openSites ;
7+ private final int len ;
8+ private static final int SOURCE = 0 ;
9+ private final int sink ;
10+ private final WeightedQuickUnionUF uf ;
11+
12+ // creates n-by-n grid, with all sites initially blocked
13+ public Percolation (int n ) {
14+ if (n <= 0 ) throw new IllegalArgumentException ();
15+ len = n ;
16+ grid = new boolean [n ][n ];
17+ sink = n * n + 1 ;
18+ uf = new WeightedQuickUnionUF (n * n + 2 );
19+ }
20+
21+ // opens the site (row, col) if it is not open already
22+ public void open (int row , int col ) {
23+ errorCheck (row , col );
24+ if (!isOpen (row , col )) openSites ++;
25+ grid [row - 1 ][col - 1 ] = true ;
26+
27+ if (row == 1 ) // Union with SOURCE
28+ uf .union (getIndex (row , col ), SOURCE );
29+ if (row == len ) // Union with sink
30+ uf .union (getIndex (row , col ), sink );
31+
32+ // Union with neighbor(s)
33+ if (row > 1 && isOpen (row - 1 , col ))
34+ uf .union (getIndex (row , col ), getIndex (row - 1 , col ));
35+ if (row < len && isOpen (row + 1 , col ))
36+ uf .union (getIndex (row , col ), getIndex (row + 1 , col ));
37+ if (col > 1 && isOpen (row , col - 1 ))
38+ uf .union (getIndex (row , col ), getIndex (row , col - 1 ));
39+ if (col < len && isOpen (row , col + 1 ))
40+ uf .union (getIndex (row , col ), getIndex (row , col + 1 ));
41+ }
42+
43+ private void errorCheck (int row , int col ) {
44+ if (row <= 0 || row > len || col <= 0 || col > len ) throw new IllegalArgumentException ();
45+ }
46+
47+ // is the site (row, col) open?
48+ public boolean isOpen (int row , int col ) {
49+ errorCheck (row , col );
50+ return grid [row - 1 ][col - 1 ];
51+ }
52+
53+ // is the site (row, col) full?
54+ public boolean isFull (int row , int col ) {
55+ errorCheck (row , col );
56+ return uf .find (getIndex (row , col )) == uf .find (SOURCE );
57+ }
58+
59+ // returns the number of open sites
60+ public int numberOfOpenSites () {
61+ return openSites ;
62+ }
63+
64+ // does the system percolate?
65+ public boolean percolates () {
66+ return uf .find (SOURCE ) == uf .find (sink );
67+ }
68+
69+ private int getIndex (int row , int col ) {
70+ return len * (row - 1 ) + col ;
71+ }
72+
73+ public static void main (String [] args ) {
74+ // testing
75+ }
76+ }
0 commit comments