Intermediate Level
Implement the closedIslandCountGrid method that counts islands fully surrounded by water.
You are given a grid where 0 represents land and 1 represents water. A closed island is a connected group of land cells that does not touch the boundary of the grid.
Return how many closed islands exist. Land cells connect only in four directions.
Any land connected to the boundary cannot be part of a closed island.
First flood fill all boundary land cells and mark them as visited. Then scan the inner cells. Whenever an unvisited land cell is found, it starts one closed island; flood fill that whole island and increase the count.
This separates open islands from closed islands clearly.
Pseudocode:
function closedIslandCountGrid(grid, rows, cols):
visited = table filled with false
flood fill every boundary cell whose value is 0
count = 0
for r from 1 to rows - 2:
for c from 1 to cols - 2:
if grid[r][c] == 0 and not visited[r][c]:
count++
flood fill this island
return count