DEV Community is a community of 665,497 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

6-10PM challenge problem #003 solution

akbhairwal
Developer

Problem#003

Count Island

``````private static int findIslandCount(int[][] binaryMatrix) {

int count = 0;
int[] arr = new int[2];
for (int i = 0; i < binaryMatrix.length; i++) {
for (int j = 0; j < binaryMatrix[0].length; j++) {

if (binaryMatrix[i][j] == 1) {
arr[0] = i;
arr[1] = j;
bfs(binaryMatrix, i, j, queue);
count++;
}
}
}

return count;
}

private static void bfs(int[][] binaryMatrix, int i, int j, Queue<int[]> queue) {

int[] arr;
int x, y;
while (queue.size() != 0) {

arr = queue.poll();
x = arr[0];
y = arr[1];
binaryMatrix[x][y] = 0;
if (x - 1 >= 0) {
if (binaryMatrix[x - 1][y] == 1) {
arr = new int[2];
arr[0] = x - 1;
arr[1] = y;
}

}
if (x + 1 < binaryMatrix.length) {
if (binaryMatrix[x + 1][y] == 1) {
arr = new int[2];
arr[0] = x + 1;
arr[1] = y;
}

}

if (y - 1 >= 0) {
if (binaryMatrix[x][y - 1] == 1) {
arr = new int[2];
arr[0] = x;
arr[1] = y - 1;
}

}
if (y + 1 < binaryMatrix[0].length) {
if (binaryMatrix[x][y + 1] == 1) {
arr = new int[2];
arr[0] = x;
arr[1] = y + 1;