Number of Enclaves solution explained

Number of Enclaves is solved by working from the outside in: start a breadth-first search from every land cell on the border, mark everything it can reach, and count the land cells that stay unmarked. Each cell is visited a constant number of times, so the solution is O(m·n) time and O(m·n) space in the worst case.

By Published 9 min read

The problem in plain words

You get a rectangular map of 0s and 1s. A 1 is a land square and a 0 is water. From a land square you may step to the land square directly above, below, left or right of it. Diagonal steps are not allowed, and you cannot cross water. A land square is an enclave square if no sequence of steps from it ever reaches a square on the outer edge of the map. Return the number of enclave squares, not the number of islands.

Example maps written for this page
Map (rows top to bottom)AnswerWhy
00000 / 01100 / 01001 / 000113The three squares in the upper left island are surrounded by water. The right-hand island touches the right edge and the bottom edge.
11 / 110Every square sits on the edge.
000 / 010 / 0001One land square in the middle, walled in by water.
100 / 010 / 0001The corner square touches the edge. The center square only meets it diagonally, which does not connect them.
0000 / 0110 / 0100 / 01000The island looks inland, but its tail reaches the bottom row.
Example maps written for this page. Scroll sideways on a small screen.

Ask first whether the grid can have a single row or a single column, because then every square is on the edge and the answer must be 0. Also confirm that you may change the input grid. Many clean solutions overwrite land with water as they go, and some interviewers want the input left alone.

What the interviewer is looking for

This is a flood-fill question with a twist in direction. Most candidates know how to count islands. The stronger signal is noticing that checking each island for an edge square is fine, but seeding the search from the edge is shorter and harder to get wrong. Interviewers also listen for how you handle recursion depth, because a long snake-shaped island can overflow a recursive DFS in Python or JavaScript.

Slow approach: search outward from every land square

Take each land square in turn and run a BFS through connected land. If the search ever lands on a border square, the starting square can escape. Otherwise it is an enclave square. With up to m·n land squares and a search of up to m·n squares for each one, the worst case is O((m·n)²). On a 500 by 500 map that is far too slow, but the idea is easy to verify, so it makes a good checker.

from collections import deque

def enclosed_land_slow(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    total = 0
    for sr in range(rows):
        for sc in range(cols):
            if grid[sr][sc] != 1:
                continue
            seen = {(sr, sc)}
            queue = deque([(sr, sc)])
            escapes = False
            while queue and not escapes:
                r, c = queue.popleft()
                if r in (0, rows - 1) or c in (0, cols - 1):
                    escapes = True
                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1 and (nr, nc) not in seen:
                        seen.add((nr, nc))
                        queue.append((nr, nc))
            if not escapes:
                total += 1
    return total
Slow version: one BFS per land square.

A middle step is to search per island instead of per square: label each island once, note whether any of its squares lies on the edge, and add the island's size when it does not. That is already O(m·n). The border-seeded version below is the same cost with less bookkeeping.

Main approach: flood from the border

Escaping is symmetric. If square A can walk to the edge, then some edge square can walk back to A along the same path. So collect every land square on the four edges, put all of them in one queue, and run a single BFS. Every land square it reaches can escape. After the search, count the land squares that were never reached. The queue starts with many sources at once, which is why this is called a multi-source BFS.

from collections import deque

def enclosed_land(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    reached = [[False] * cols for _ in range(rows)]
    queue = deque()
    for r in range(rows):
        for c in range(cols):
            on_edge = r in (0, rows - 1) or c in (0, cols - 1)
            if on_edge and grid[r][c] == 1:
                reached[r][c] = True
                queue.append((r, c))
    while queue:
        r, c = queue.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1 and not reached[nr][nc]:
                reached[nr][nc] = True
                queue.append((nr, nc))
    return sum(
        1
        for r in range(rows)
        for c in range(cols)
        if grid[r][c] == 1 and not reached[r][c]
    )
Python: multi-source BFS from the edge, O(m·n) time and space.
function enclosedLand(grid) {
  const rows = grid.length;
  const cols = rows ? grid[0].length : 0;
  const reached = new Uint8Array(rows * cols);
  const queue = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const onEdge = r === 0 || r === rows - 1 || c === 0 || c === cols - 1;
      if (onEdge && grid[r][c] === 1) {
        reached[r * cols + c] = 1;
        queue.push(r * cols + c);
      }
    }
  }
  const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  for (let head = 0; head < queue.length; head++) {
    const r = Math.floor(queue[head] / cols);
    const c = queue[head] % cols;
    for (const [dr, dc] of moves) {
      const nr = r + dr;
      const nc = c + dc;
      if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
      const id = nr * cols + nc;
      if (grid[nr][nc] === 1 && !reached[id]) {
        reached[id] = 1;
        queue.push(id);
      }
    }
  }
  let count = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === 1 && !reached[r * cols + c]) count++;
    }
  }
  return count;
}
JavaScript: the same search with a flat array as the queue and a moving head index.

Using a head index instead of queue.shift() matters in JavaScript. shift moves every element, which turns a linear BFS into a quadratic one on large maps.

Tracing the first map

  1. Seed the queueEdge land in 00000 / 01100 / 01001 / 00011 is (2,4), (3,3) and (3,4). All three start as reached.
  2. ExpandFrom those squares, the only land neighbors are each other, so the search stops after three squares.
  3. Count the restLand squares (1,1), (1,2) and (2,1) were never reached. The answer is 3.

Complexity

Cost of each approach on an m by n map
ApproachTimeExtra spaceComment
BFS from every land squareO((m·n)²)O(m·n)Correct but quadratic in the number of squares
Label islands, check edgesO(m·n)O(m·n)Fine, more bookkeeping
Multi-source BFS from the edgeO(m·n)O(m·n)Shortest to write and explain
Union-find with a virtual edge nodeNear O(m·n)O(m·n)Useful if land is added over time
Cost of each approach on an m by n map. Scroll sideways on a small screen.

If you are allowed to overwrite the grid, set reached land to 0 instead of keeping a separate array. The queue can still hold O(m·n) squares in the worst case, so the space bound does not change, but the constant drops.

Edge cases to test

  • One row or one column: every square is on the edge, so the answer is 0.
  • All water: the answer is 0 and the queue starts empty.
  • All land: every square connects to the edge, so the answer is 0.
  • Diagonal contact only, like the 100 / 010 / 000 map. The center square is still an enclave.
  • A long winding island that reaches the edge only at its far tip. This catches searches that stop too early and recursive versions that run out of stack.
  • Two separate inland islands. Both sizes must be added.

Mistakes that cost points

  • Returning the number of enclosed islands instead of the number of enclosed squares.
  • Allowing diagonal moves. The rule is four directions only.
  • Marking a square as reached when it is popped instead of when it is pushed, so the same square enters the queue several times.
  • Seeding only the top and left edges, or counting corner squares twice in a way that breaks the marking.
  • Writing a recursive DFS without mentioning depth. A 300 by 300 spiral can go tens of thousands of calls deep, past default limits in Python and in many JavaScript engines.

How to explain it out loud

Fictional example

Talking through the border idea
Candidate
Rather than asking whether each land square can reach the edge, I will start from the edge and see which land squares it can reach. Reachability through land works the same in both directions.
Candidate
I push every edge land square into one queue, run BFS, and mark what I touch. Anything unmarked at the end is enclosed, so I count those.
Candidate
Each square enters the queue at most once, so time and space are both linear in the grid size. I am using BFS with an explicit queue so a long island cannot blow the call stack.

Where to go next

Count Servers That Communicate is a grid problem where no search is needed at all, which is a useful contrast. Longest Cycle in a Graph moves from grids to directed edges and shows how visit marks can also carry timestamps. Background on BFS, queues and visited sets is on the data structure interview questions page.

Rehearsing with Natively

For grid and search questions, Natively can read the problem from a screenshot during practice and propose an approach, which you can compare with your own sketch once you have one. It transcribes your spoken walkthrough on your computer, so after a mock round you can see whether you explained the border trick and the stack-depth risk clearly. See how AI helps in coding interviews.

Questions people ask

What is the best approach for Number of Enclaves?

Run one breadth-first search seeded with every land cell on the border and mark what it reaches. The land cells left unmarked are enclosed. It takes O(m·n) time and O(m·n) space in the worst case.

Why start the search from the border instead of from each land cell?

Reaching the edge is symmetric, so one search from all edge land finds every escapable cell at once. Searching from each land cell repeats work and can cost O((m·n)²).

Should I use DFS or BFS for Number of Enclaves?

Both are correct. BFS with an explicit queue, or an iterative DFS with a stack, avoids recursion limits on long winding islands, which matters in Python and JavaScript.

Do diagonal cells count as connected?

No. Movement is only up, down, left and right, so land that touches the edge only diagonally does not help an inner cell escape.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP