Problem statement

https://leetcode.com/problems/number-of-enclaves/

Solution

We need to put all border into stack/queue and then perform dfs/bfs and color visited nodes. Then traverse once again and collect not visited nodes.

Complexity

It is O(mn) for time and space.

Code

class Solution:
    def numEnclaves(self, grid):
        n, m = len(grid[0]), len(grid)
        b1  = [(0, i) for i in range(n)]  + [(i, 0) for i in range(1, m)]
        b2 = [(m-1, i) for i in range(n)] + [(i, n-1) for i in range(m-1)]
        
        V = set()
        q = deque([(x, y) for x, y in b1 + b2 if grid[x][y] == 1])
        while q:
            i, j = q.popleft()
            grid[i][j] = 2
            for x, y in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
                if not 0 <= x < m or not 0 <= y < n or grid[x][y] != 1 or (x, y) in V: continue
                V.add((x, y))
                q += [(x, y)]
      
        return sum(grid[i][j] == 1 for i, j in product(range(m), range(n)))