题目:
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.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j]
is either0
or1
.
思路:
这题其实理解了什么是enclave就行了,其实就是不和矩形边界相连的地块。这样只要用dfs/bfs把与矩阵边界相邻的地块从1置为0,之后遍历矩阵,剩下的所有1就是飞地。本题用的是dfs,遍历4条边界的时候,如果当前格子为1,即这是陆地,则用dfs进行搜索并置0,最后遍历矩阵获得答案。
代码:
class Solution {
public:
int numEnclaves(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int i = 0 ; i < n; i++) {
if (grid[0][i]) dfs(grid, 0, i);
if (grid[m - 1][i]) dfs(grid, m - 1, i);
}
for (int j = 0; j < m; j++) {
if (grid[j][0]) dfs(grid, j, 0);
if (grid[j][n - 1]) dfs(grid, j, n - 1);
}
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j])
count++;
}
}
return count;
}
private:
void dfs(vector<vector<int>> &grid, int x, int y) {
int m = grid.size(), n = grid[0].size();
if (x < 0 || y < 0 || x >= m || y >= n) return;
if (grid[x][y] == 0) return;
grid[x][y] = 0;
dfs(grid, x - 1, y);
dfs(grid, x + 1, y);
dfs(grid, x, y + 1);
dfs(grid, x, y - 1);
}
};