summaryrefslogtreecommitdiffstats
path: root/Algorithms/Part-I/1-Percolation/Percolation.java
blob: efe79e80942890aa903f4b035cbc0006e6531cfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* vim: set expandtab tabstop=4 shiftwidth=4 : */

public class Percolation
{
    private int N;
    private byte[] opened;
    private WeightedQuickUnionUF uf;

    // create N-by-N grid, with all sites blocked
    public Percolation(int N)
    {
        this.N = N;
        int n = (N*N)+2;
        uf = new WeightedQuickUnionUF(n);
        opened = new byte[n];
        opened[0] = 1;
        opened[n-1] = 1;
    }

    // open site (row i, column j) if it is not already
    public void open(int i, int j)
    {
        if (i < 1 || j < 1 || i > N || j > N)
            throw new java.lang.IndexOutOfBoundsException("check your indexes");
        int x = (j-1)*N+i;
        if (opened[x] == 1) return;
        opened[x] = 1;
        if (i > 1 && opened[x-1] == 1) uf.union(x, x-1);
        if (i < N && opened[x+1] == 1) uf.union(x, x+1);
        if (j == 1) {
            uf.union(x, 0);
            if (opened[x+N] == 1) uf.union(x, x+N);
        }
        else if (j == N) {
            uf.union(x, N*N+1);
            if (opened[x-N] == 1) uf.union(x, x-N);
        } else {
            if (opened[x-N] == 1) uf.union(x, x-N);
            if (opened[x+N] == 1) uf.union(x, x+N);
        }
    }

    // is site (row i, column j) open?
    public boolean isOpen(int i, int j)
    {
        if (i < 1 || j < 1 || i > N || j > N)
            throw new java.lang.IndexOutOfBoundsException("check your indexes");
        return (opened[(j-1)*N+i] == 1);
    }

    // is site (row i, column j) full?
    public boolean isFull(int i, int j)
    {
        if (i < 1 || j < 1 || i > N || j > N)
            throw new java.lang.IndexOutOfBoundsException("check your indexes");
        int x = (j-1)*N+i;
        return ((opened[x] == 1) && (uf.find(x) == 0));
    }

    // does the system percolate?
    public boolean percolates()
    {
        return (uf.find(0) == uf.find(N*N+1));
    }
}