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.
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