oneby7

Graphs Grids as graphs

440. Number of Enclaves

Medium

You are given a map as a grid of integers, grid, with m rows and n columns. A cell that holds 1 is land, and a cell that holds 0 is water.

From a land cell you may walk one step up, down, left or right onto another land cell. You cannot step onto water, and you cannot step diagonally. From a land cell on the edge of the grid, one more step takes you off the grid.

Return the number of land cells from which you can never walk off the grid.

Example 1

000100010110011000000010110000

Input: grid = [[0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0]]

Output: 4

Explanation: The group of three cells on the left and the single cell at row 3, column 4 cannot reach the edge. The land at row 2, column 2 touches the land at row 1, column 3 only at a corner, so it cannot step there.

Example 2

011001100110

Input: grid = [[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0]]

Output: 0

Explanation: The two middle cells are not on the edge, but they can step up to the top row or down to the bottom row, and walk off from there.

Example 3

101010101

Input: grid = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]

Output: 1

Explanation: The four corners are on the edge. The middle cell touches them only at corners, so it is cut off.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • m == grid.length, n == grid[i].length
  • 1 ≤ m, n ≤ 500
  • grid[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.