池塘个数/岛屿个数
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
bool isCheck(int i, int j, int M, int N)
{
if (i >= 0 && i < M && j >= 0 && j < N)
return true;
else
return false;
}
void bfs(vector<vector<int>> &ivec, vector<vector<bool>> &flag, vector<int> &a, vector<int> &b, int x, int y, int M, int N)
{
queue<pair<int,int>> q;
q.push(make_pair(x, y));
flag[x][y] = false;
while (!q.empty())
{
pair<int, int> p = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int newX = p.first + a[i];
int newY = p.second + b[i];
if (isCheck(newX, newY, M, N) && ivec[newX][newY] == 1 && flag[newX][newY])
{
q.push({ newX, newY });
flag[newX][newY] = false;
}
}
}
}
int main()
{
int M, N;
while (cin >> M >> N)
{
int num;
vector<vector<int>> ivec(M, vector<int>(N, 0));
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
cin >> ivec[i][j];
}
vector<vector<bool>> flag(M, vector<bool>(N, true));
vector<int> a = { 1, -1, 0, 0 };
vector<int> b = { 0, 0, 1, -1 };
int count = 0;
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (ivec[i][j] == 1 && flag[i][j])
{
bfs(ivec, flag, a, b, i, j, M, N);
count++;
}
}
}
cout << count << endl;
}
return 0;
}