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.

Example 1

Input
grid (int[][]) = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
rows (int) = 5
cols (int) = 8
Returns (int) 2

Example 2

Input
grid (int[][]) = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
rows (int) = 3
cols (int) = 5
Returns (int) 1

Example 3

Input
grid (int[][]) = [[1,1,1],[1,0,1],[1,1,1]]
rows (int) = 3
cols (int) = 3
Returns (int) 1

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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.