← DiffPush

Number of Enclaves

Standard Bar Graphs · Traversal Problems O(m * n) · O(m * n)

Counting the Landlocked Plots

A harbour authority maps its estate as a grid of dock-access plots (1) and sealed lots (0). A plot grants an exit if a worker can walk across adjacent plots to the estate boundary and step off. The audit wants the number of plots from which no such walk exists — the fully landlocked ones, however large their inland cluster is.

Input: An m x n binary matrix grid where 0 is a sealed lot and 1 is a dock-access plot.

Output: Return the number of land cells from which the grid boundary cannot be reached by 4-directional moves.

Constraints

Examples

Example 1

Input: {"grid":[[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]}
Output: 3
The three inland plots form one cluster sealed off by lots on every side.

Example 2

Input: {"grid":[[1,0],[0,1]]}
Output: 0
Both plots sit on the boundary — each can step straight off the estate.

Solve this in your browser →

Also on LeetCode ↗