题目来源:101. 孤岛的总面积
C++题解:在卡码网KamaCoder 100. 岛屿的最大面积-CSDN基础上加了个孤岛flg进行修改
#include <iostream>
#include <vector>
#include <queue>
#include <stdio.h>
using namespace std;
int res = 0, tmp = 0;
bool flg = false;
int bfs(vector<vector<int>> &grid, vector<vector<int>>&visited, int &tmp, int x, int y, bool& flg){
queue<pair<int, int>> que;
que.push({x, y});
if(visited[x][y]==1 || grid[x][y] == 0) return tmp;
if(x == 1 || x == grid.size()-1 || y == 1 || y == grid[0].size()-1) flg = true;
visited[x][y] = true;
tmp = tmp + 1;
if(x-1 > 0) {
if(grid[x-1][y] == 1 && visited[x-1][y] == 0){
que.push({x-1, y});
}
}
if(y-1 > 0) {
if(grid[x][y-1] == 1 && visited[x][y-1] == 0){
que.push({x, y-1});
}
}
if(x+1 < grid.size()) {
if(grid[x+1][y] == 1 && visited[x+1][y] == 0){
que.push({x+1, y});
}
}
if(y+1 < grid[0].size()) {
if(grid[x][y+1] == 1 && visited[x][y+1] == 0){
que.push({x, y+1});
}
}
while(!que.empty()){
pair<int, int> cur = que.front();
que.pop();
int curx = cur.first, cury = cur.second;
tmp = bfs(grid, visited, tmp, curx, cury, flg);
}
return tmp;
}
int main(){
int N, M;
cin >> N >> M;
vector<vector<int>> grid(N+1, vector<int>(M+1, 0));
for(int i = 1; i <= N; i++) {
for(int j = 1; j <= M; j++) {
cin>>grid[i][j];
}
}
vector<vector<int>> visited(N+1, vector<int>(M+1, 0));
for(int i = 1; i <= N; i++) {
for(int j = 1; j <= M; j++) {
if(visited[i][j] == 1) continue;
tmp = 0;
flg = false;
tmp = bfs(grid, visited, tmp, i, j, flg);
if(!flg) res = res + tmp;
}
}
cout<<res;
return 0;
}