Number of Enclaves Problem
Description
LeetCode Problem 1020.
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.
Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.
Example 1:

Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Example 2:

Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500grid[i][j]is either0or1.
Solution
Approach: Flood Fill From the Boundary
Instead of asking, for every land cell, whether it can reach the edge, turn the question around: which land cells can be reached from the edge? Those are exactly the cells that can walk off the grid, and every other land cell is enclosed.
- Put every land cell on the first or last row or column into a queue and turn it into sea (
0) so it is not visited twice. - Run a BFS: pop a cell, and turn each land neighbor (up, down, left, right) into sea and push it.
- When the queue is empty, all land connected to the boundary is gone. Count the
1s that are left.
We use BFS rather than recursive DFS on purpose: the grid can be 500 x 500, and a long winding strip of land would make a recursive search go hundreds of thousands of calls deep and overflow the stack.
Complexity: O(m * n) time, as every cell is visited a constant number of times, and O(m * n) extra space for the queue in the worst case.
from collections import deque
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# Start from every land cell on the boundary: these can walk off directly.
queue = deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (i == 0 or i == m - 1 or j == 0 or j == n - 1):
grid[i][j] = 0 # sink it, so it is not counted or visited again
queue.append((i, j))
# Everything reachable from the boundary can walk off too: sink it.
while queue:
i, j = queue.popleft()
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
grid[x][y] = 0
queue.append((x, y))
# The land that is left is enclosed.
return sum(sum(row) for row in grid)