题目:
- 给你一个大小为
m x n
的二进制矩阵grid
,其中0
表示一个海洋单元格、1
表示一个陆地单元格。 - 一次 移动 是指从一个陆地单元格走到另一个相邻(上、下、左、右)的陆地单元格或跨过
grid
的边界。 - 返回网格中 无法 在任意次数的移动中离开网格边界的陆地单元格的数量。
示例1:
- 输入: g r i d = [ [ 0 , 0 , 0 , 0 ] , [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] ] grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] grid=[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
- 输出: 3 3 3
- 解释: 有三个 1 被 0 包围。一个 1 没有被包围,因为它在边界上。
示例2:
- 输入: g r i d = [ [ 0 , 1 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] ] grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] grid=[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
- 输出: 0 0 0
- 解释: 所有 1 都在边界上或可以到达边界。
解题思路:(BFS)
先遍历四周(也就是与边界接壤的网格),若为1,就BFS该陆地相接壤的陆地,将其置为0。四周处理完后剩下的区域就是没有与边界接壤的陆地,再全局执行一遍BFS,遇到陆地就将计数器cnt++
,最终返回结果cnt
。
C++版整体代码(BFS):
class Solution {
public:
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
int cnt;
void bfs(vector<vector<int>>& grid, int x, int y){
queue<pair<int, int>> q;
q.push({x, y});
grid[x][y] = 0;
cnt++;
while(!q.empty()){
pair<int, int> cur = q.front();
q.pop();
int curx = cur.first, cury = cur.second;
for(int i = 0; i < 4; i++){
int nextx = curx + dx[i], nexty = cury + dy[i];
if(nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
if(grid[nextx][nexty] == 1){
q.push({nextx, nexty});
cnt++;
grid[nextx][nexty] = 0;
}
}
}
}
int numEnclaves(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; i++){
if(grid[i][0] == 1) bfs(grid, i, 0);
if(grid[i][m - 1] == 1) bfs(grid, i, m - 1);
}
for(int i = 0; i < m; i++){
if(grid[0][i] == 1) bfs(grid, 0, i);
if(grid[n - 1][i] == 1) bfs(grid, n - 1, i);
}
cnt = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == 1){
bfs(grid, i, j);
}
}
}
return cnt;
}
};
C++版整体代码(DFS):
class Solution {
public:
int cnt;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs(vector<vector<int>>& grid, int x, int y){
grid[x][y] = 0;
cnt++;
for(int i = 0; i < 4; i++){
int nextx = x + dx[i], nexty = y + dy[i];
if(nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
if(grid[nextx][nexty] == 0) continue;
dfs(grid, nextx, nexty);
}
return;
}
int numEnclaves(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; i++){
if(grid[i][0] == 1) dfs(grid, i, 0);
if(grid[i][m - 1] == 1) dfs(grid, i, m - 1);
}
for(int i = 0; i < m; i++){
if(grid[0][i] == 1) dfs(grid, 0, i);
if(grid[n - 1][i] == 1) dfs(grid, n - 1, i);
}
cnt = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == 1) dfs(grid, i, j);
}
}
return cnt;
}
};