Paint a Boolean matrix
PaintingIterative.javapublic static void flipColor(boolean[][] A, int x, int y) {
int[][] dir = new int[][]{new int[]{0, 1}, new int[]{0, -1},
new int[]{1, 0}, new int[]{-1, 0}};
boolean color = A[x][y];
Queue<Pair<Integer, Integer>> q = new LinkedList<>();
A[x][y] = !A[x][y]; // Flips.
q.add(new Pair<>(x, y));
while (!q.isEmpty()) {
Pair<Integer, Integer> curr = q.element();
for (int[] d : dir) {
Pair<Integer, Integer> next = new Pair<>(
curr.getFirst() + d[0], curr.getSecond() + d[1]);
if (next.getFirst() >= 0 && next.getFirst() < A.length
&& next.getSecond() >= 0
&& next.getSecond() < A[next.getFirst()].length
&& A[next.getFirst()][next.getSecond()] == color) {
// Flips the color.
A[next.getFirst()][next.getSecond()] = !A[next.getFirst()][next
.getSecond()];
q.add(next);
}
}
q.remove();
}
}
PaintingRecursive.java
public static void flipColor(boolean[][] A, int x, int y) {
int[][] dir = new int[][]{new int[]{0, 1}, new int[]{0, -1},
new int[]{1, 0}, new int[]{-1, 0}};
boolean color = A[x][y];
A[x][y] = !A[x][y]; // Flips.
for (int[] d : dir) {
int nx = x + d[0], ny = y + d[1];
if (nx >= 0 && nx < A.length && ny >= 0 && ny < A[nx].length
&& A[nx][ny] == color) {
flipColor(A, nx, ny);
}
}
}