Skip to content

1020. Number of Enclaves

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[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 isn't enclosed because its on the boundary.

Example 2:

Input: [[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.

Note:

  1. 1 <= A.length <= 500
  2. 1 <= A[i].length <= 500
  3. 0 <= A[i][j] <= 1
  4. All rows have the same size.

Analysis

What this question is asking: give a grid, count all the land that is disconnected to the border.

Step 1: find all the 1 from the borders.

Step 2: "flood fill" from border to all the internal land.

Step 3: recursively fill all the neighbours of current land.

Step 4: count the number of 1s in the grid.

Time: O(m \times n)

Space: O(m \times n) possible stack space allocated for the dfs call

Code

class Solution {
public:
    int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
    int m, n;

    void dfs(vector<vector<int>>& A, int x, int y) {        
        if (x >= m || y >= n || x < 0 || y < 0 || A[x][y] == 0)
            return ;
        A[x][y] = 0;
        for (auto d : dir) {
            dfs(A, x + d[0], y + d[1]);
        }
    }
    int numEnclaves(vector<vector<int>>& A) {

        m = A.size(), n = A[0].size();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                // here we do a trick: 1 * 0, 0 * 1 and 0 * 0 == 0
                // equal to i == 0 || j == 0
                if (i * j == 0 || i == m - 1 || j == n - 1) 
                  dfs(A, i, j);
            }
        }

        int res = 0;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (A[i][j] == 1) res ++;
        return res;

    }
};

Last update: March 31, 2022