PPractick

DSA interview question

Number of Enclaves

Medium · Data structures · Topics: graph, dfs, bfs, matrix

The problem

A map grid marks land with 1 and sea with 0. An enclave cell is a land cell from which you can't walk off the edge of the map, moving 4-directionally over land. Count the enclave cells. Like surrounded regions, reverse the question. Flood-fill from every land cell on the border; everything reached can walk off. The land cells left unreached are enclaves.

Example: [[0,0,0,0], [1,0,1,0], [0,1,1,0], [0,0,0,0]] → 3.

Function signature

int numEnclaves(vector<vector<int>> grid);

Test cases

InputOutputExplanation
[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]3The left 1 is on the border
[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]0All connected to the top edge
[[0,0,0],[0,1,0],[0,0,0]]1
[[1,1,1],[1,0,1],[1,1,1]]0A ring on the border
[[1]]0

(Confirm: 4-directional moves; the answer counts cells, not regions.)

How interviewers phrase it

Clarifying questions to ask

  1. Count cells or regions? (Cells.)
  2. 4-directional? (Yes.)
  3. May I modify the grid? (Yes; otherwise copy it.)

Follow-ups to expect

  1. "Why flood from the border?"
  2. "How is this related to surrounded regions?"
  3. "Could you count per region?"
  4. "Memory?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in