Graphs Grids as graphs
440. Number of Enclaves
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
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]]
4Explanation: 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
Input: grid = [[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0]]
0Explanation: 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
Input: grid = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
1Explanation: 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.
Constraints
m == grid.length,n == grid[i].length1 ≤ m, n ≤ 500grid[i][j]is 0 or 1.
Clarifying questions
What you would ask an interviewer before writing any code.