Intermediate Level

Implement the enclaveLandCellCount method that counts land cells unable to reach the boundary.

You are given a grid where 1 represents land and 0 represents water. A land cell can move to another land cell in four directions.

Return the number of land cells that cannot reach any boundary cell. These cells are completely trapped inside the grid.

Example 1

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

Example 2

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

Example 3

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

Start from all boundary land cells and mark every land cell connected to them.

Any land reached from the boundary is not an enclave because it can escape the grid. After this flood fill, count the remaining land cells that were not visited.

This approach avoids checking escape paths separately for every land cell.

Pseudocode:

function enclaveLandCellCount(grid, rows, cols):
    visited = rows by cols table filled with false
    queue = empty queue
    add every boundary land cell to queue and mark visited
    while queue is not empty:
        cell = remove front
        for each four-direction neighbor:
            if neighbor is inside and grid value is 1 and not visited:
                mark visited
                add neighbor to queue
    answer = 0
    for each cell:
        if grid[cell] == 1 and not visited[cell]:
            answer++
    return answer
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.