Loading content...
You are given a two-dimensional binary matrix representing a geographical map. In this matrix, the value 0 represents water (ocean cells), and the value 1 represents land (terrain cells).
From any land cell, you can traverse to an adjacent land cell in any of the four cardinal directions: up, down, left, or right. A land cell is considered reachable to the boundary if there exists a path of consecutive land cells leading from that cell to any cell on the edge (boundary) of the grid.
Your task is to count and return the total number of isolated land cells — land cells from which it is impossible to reach any boundary edge of the grid through any sequence of valid moves across adjacent land cells.
In other words, count all land cells that are completely enclosed by water or other land cells such that no path exists from them to the grid's perimeter.
grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]3The grid contains a cluster of three land cells (value 1) in the interior that are completely surrounded by water cells (value 0). The land cell at position [1,0] is on the left boundary, so it can reach the edge. However, the three land cells at positions [1,2], [2,1], and [2,2] form an enclosed region with no path to any boundary. Therefore, the answer is 3.
grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]0All land cells in this grid are either directly on the boundary or connected to land cells that touch the boundary. The land cells at [0,1] and [0,2] are on the top boundary. The remaining land cells at [1,2] and [2,2] are directly connected to [0,2] through vertical adjacency. Since every land cell can trace a path to the boundary, no isolated land cells exist, and the answer is 0.
grid = [[0,0,0],[0,1,0],[0,0,0]]1This simple 3×3 grid has a single land cell at the center position [1,1]. This cell is completely surrounded by water cells on all four sides and has no path to any edge of the grid. Since it cannot reach the boundary, it is counted as isolated, giving an answer of 1.
Constraints