enum Mode ONE TWO Percolation data type Created with IntelliJ IDEA Use

  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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
enum Mode
{
ONE, TWO
}
/**
* Percolation data type
* Created with IntelliJ IDEA.
* User: Andrey Kudryavtsev
* Date: 07.11.13
* Time: 22:04
*/
public class Percolation
{
private int size;
private WeightedQuickUF QUF;
private Grid grid;
public Percolation(byte[][] matrix, int size)
{
this(matrix, size, Mode.ONE);
}
public Percolation(byte[][] matrix, int size, Mode mode)
{
this.size = size;
grid = new Grid(size, mode);
QUF = new WeightedQuickUF(size * size + 2);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (matrix[i][j] == 1)
open(i, j);
}
}
}
/**
* open site (row i, column j) if it is not already
*
* @param i row
* @param j column
*/
public void open(int i, int j)
{
if (!isOpen(i, j))
{
int index = getIndex(i, j);
if (i == 0)
{
QUF.union(0, index);
}
if (i == size - 1)
{
QUF.union(1, index);
}
grid.get(i, j).setStatus(Status.OPEN);
Point[] neighbours = grid.getNeighbours(new Point(i, j));
for (Point p : neighbours)
{
if (p.isValid(size) && isOpen(p.getX(), p.getY()))
QUF.union(index, getIndex(p.getX(), p.getY()));
}
}
}
/**
* Is site (row i, column j) open?
*
* @param i row
* @param j column
* @return true if yes
*/
public boolean isOpen(int i, int j)
{
return grid.get(i, j).getStatus() != Status.CLOSED;
}
/**
* Does the system percolate?
*
* @return true if yes
*/
public boolean isPercolated()
{
return QUF.isConnected(0, 1);
}
public boolean isFull(int i, int j)
{
int index = getIndex(i, j);
return isOpen(i, j) && QUF.isConnected(0, index);
}
/**
* Return index for 1-dim array
*
* @param i row
* @param j column
* @return index for 1-dim array
*/
public int getIndex(int i, int j)
{
return size * i + j + 2;
}
}