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 it's 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 <= A.length <= 5001 <= A[i].length <= 5000 <= A[i][j] <= 1- All rows have the same size.
Analysis¶
What this question is asking: given a grid, count all the land that is disconnected from the border.
Step 1: find all the 1s from the borders.
Step 2: "flood fill" from the border to all the internal land.
Step 3: recursively fill all the neighbours of the 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;
}
};