Intermediate Level

Implement the numberOfIslandsBfsCount method that counts islands in a grid using breadth-first search.

The input contains a binary grid with rows and cols. A value of 1 represents land, and a value of 0 represents water.

An island is a group of connected land cells. Cells are connected only horizontally or vertically, not diagonally.

Your task is to count how many separate islands exist in the grid.

Example 1
Input:
grid (int[][]) = [[1,1,0],[0,1,0],[1,0,1]]
rows (int) = 3
cols (int) = 3
Return:
(int) 3
Example 2
Input:
grid (int[][]) = [[1,1],[1,1]]
rows (int) = 2
cols (int) = 2
Return:
(int) 1
Example 3
Input:
grid (int[][]) = [[1,0],[0,1]]
rows (int) = 2
cols (int) = 2
Return:
(int) 2

Scan every cell in the grid.

When an unvisited land cell is found, it is the start of a new island. Increase the island count and use BFS to visit all land cells connected to it. Mark those cells as visited so they are not counted again.

Continue scanning until all cells are processed.

Pseudocode:

function numberOfIslandsBfsCount(grid, rows, cols):
    visited = grid of false values
    count = 0
    directions = up, down, left, right
    for r from 0 to rows - 1:
        for c from 0 to cols - 1:
            if grid[r][c] == 1 and visited[r][c] == false:
                count++
                queue = empty queue
                push (r, c) into queue
                visited[r][c] = true
                while queue is not empty:
                    cell = pop queue
                    for each direction:
                        nr = cell.row + direction.row
                        nc = cell.col + direction.col
                        if position is valid and grid[nr][nc] == 1 and visited[nr][nc] == false:
                            visited[nr][nc] = true
                            push (nr, nc) into queue
    return count
Run your code to see the result.