Skip to main content
Back to problems
Leetcode
Medium
Matrices
Graphs
Queues
Amazon
Microsoft
Number Of Enclaves

Count the land cells in a grid that cannot reach the boundary by moving through adjacent land cells.

Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

You are given a 2D grid of binary values where 1 represents land and 0 represents water. A land cell is part of an enclave if it belongs to a connected region of land that cannot reach any border of the grid by moving only up, down, left, or right through land cells.

Return the number of land cells that are enclosed in this way.

In other words, first identify every land cell that can be connected to the boundary, then count the remaining land cells.

Input Format

  • An integer matrix grid with grid[i][j] in {0, 1}.
  • 1 means land and 0 means water.

Output Format

  • Return a single integer: the total number of land cells that are not connected to any boundary cell.

Constraints

  • Movement is allowed only in 4 directions: up, down, left, right.
  • A cell is on the boundary if it lies in the first/last row or first/last column.
  • The grid contains at least one cell.
Examples
Sample cases returned by the problem API.

Example 1

Input

grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]

Output

3

Explanation

The land cells at positions (1,2), (2,1), and (2,2) are enclosed. The land cell at (1,0) touches the boundary, so it is not counted.

Example 2

Input

grid = [[0,1,1,0],[0,0,1,0],[0,0,0,0]]

Output

0

Explanation

Every land cell can reach the boundary through adjacent land cells, so there are no enclaves.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.