题目链接:孤岛的总面积
本题需要求的是孤岛的面积,孤岛是那些位于矩阵内部、所有单元格都不接触边缘的岛屿。
那么如果一个岛屿不是孤岛,那么其在搜索时,一定会产生越界,利用一个标记位来对越界进行标记,如果产生越界就不统计这个岛的面积。
#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int num;
void dfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y, int& flag){
for(int i = 0; i < 4; i++){
int nextx = x + dir[i][0];
int nexty = y + dir[i][1];
if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
flag = 1;
continue;
}else{
if(graph[nextx][nexty] == 1 && !visited[nextx][nexty]){
visited[nextx][nexty] = true;
num++;
dfs(graph, visited, nextx, nexty, flag);
}
}
}
}
void bfs(vector<vector<int>>& graph, vector<vector<bool>>& visited, int x, int y, int& flag){
queue<pair<int, int>> que;
que.push({x, y});
while(!que.empty()){
pair<int, int> cur = que.front();
que.pop();
for(int i = 0; i < 4; i++){
int nextx = cur.first + dir[i][0];
int nexty = cur.second + dir[i][1];
if(nextx < 0 || nextx >= graph.size() || nexty < 0 || nexty >= graph[0].size()){
flag = 1;
continue;
}else{
if(graph[nextx][nexty] == 1 && !visited[nextx][nexty]){
visited[nextx][nexty] = true;
num++;
que.push({nextx, nexty});
}
}
}
}
}
int main(){
int n,m;
cin >> n >> m;
vector<vector<int>> graph(n, vector<int>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >>graph[i][j];
}
}
int ans = 0;
vector<vector<bool>> visited(n, vector<bool>(m, false));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(graph[i][j] == 1 && !visited[i][j]){
num = 1;
visited[i][j] = true;
int flag = 0;
//dfs(graph, visited, i, j, flag);
bfs(graph, visited, i, j, flag);
if(flag == 0){
ans += num;
}
}
}
}
cout << ans << endl;
}