DEV Community

akbhairwal
akbhairwal

Posted on

1 2

6-10PM challenge problem #003 solution

Problem#003

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);
            }

        }

    }

}

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay