6-10PM challenge problem #003 solution
akbhairwal
Posted on October 5, 2019
Count Island
private static int findIslandCount(int[][] binaryMatrix) {
int count = 0;
int[] arr = new int[2];
Queue<int[]> queue = new LinkedList<int[]>();
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;
queue.add(arr);
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;
queue.add(arr);
}
}
if (x + 1 < binaryMatrix.length) {
if (binaryMatrix[x + 1][y] == 1) {
arr = new int[2];
arr[0] = x + 1;
arr[1] = y;
queue.add(arr);
}
}
if (y - 1 >= 0) {
if (binaryMatrix[x][y - 1] == 1) {
arr = new int[2];
arr[0] = x;
arr[1] = y - 1;
queue.add(arr);
}
}
if (y + 1 < binaryMatrix[0].length) {
if (binaryMatrix[x][y + 1] == 1) {
arr = new int[2];
arr[0] = x;
arr[1] = y + 1;
queue.add(arr);
}
}
}
}
💖 💪 🙅 🚩
akbhairwal
Posted on October 5, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.