考察图的连通性,主要用到的深度搜索遍历,代码很简单,仔细读就容易读懂la
#include<iostream>
#include<vector>
using namespace std;
struct node
{
int x, y;
}dir[4];
vector<vector<int>> vec, flag;
bool pl;
void DBFS(int a, int b)
{
flag[a][b]=1;
if (vec[a][b] > 1)
pl = true;
for (int i = 0; i < 4; i++)
{
int c = a + dir[i].x, d = b + dir[i].y;
if (vec[c][d] && !flag[c][d])
DBFS(c, d);
}
}
int main()
{
dir[0].x = 0; dir[0].y = -1;
dir[1].x = -1; dir[1].y = 0;
dir[2].x = 1; dir[2].y = 0;
dir[3].x = 0; dir[3].y = 1;
int N, M;
cin >> N >> M;
vec.resize(N + 2);
vec[0].resize(M + 2,0);
vec[N+1].resize(M + 2,0);
flag.resize(N + 1);
for (int i = 1; i <= N; i++)
{
flag[i].resize(M + 1);
vec[i].resize(M + 2,0);
string str;
cin >> str;
for (int j = 0; j < M; j++)
vec[i][j+1]=str[j]-'0';
}
int dao = 0, bao = 0;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
if (vec[i][j] && !flag[i][j])
{
pl = false;
dao++;
DBFS(i, j);
if (pl)
bao++;
}
cout << dao << ' ' << bao;
return 0;
}