[LeetCode] Number of Enclaves

1020. Number of Enclaves

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
void floodfill(vector<vector<int>>& g, int y, int x) {
if(0 <= y and y < g.size() and 0 <= x and x < g[0].size() and g[y][x] == 1) {
g[y][x] = 0;
floodfill(g,y+1,x);
floodfill(g,y-1,x);
floodfill(g,y,x+1);
floodfill(g,y,x-1);
}

}
public:
int numEnclaves(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; i++) {
floodfill(grid,i,0);
floodfill(grid,i,m-1);
}
for(int i = 0; i < m; i++) {
floodfill(grid,0,i);
floodfill(grid,n-1,i);
}

int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
res += grid[i][j];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/23/PS/LeetCode/number-of-enclaves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.