用bfs,dfs判断图的连通性,核心在于,搜到合法的某点,把于其联通的点全找到并记录或改判
题目链接
ACcode(dfs)
#include<bits/stdc++.h>
using namespace std;
int n, m;
char a[105][105];
int ans = 0;
int xx[12] = { 0,0,1,-1,2,-2,0,0,1,-1,1,-1 };
int yy[12] = { 1,-1,0,0,0,0,2,-2,1,1,-1,-1 };
void dfs(int x, int y) {
if (x<1 || x>n || y<1 || y>m || a[x][y] != '#')return;
a[x][y] = '-';
for (int i = 0;i < 12;i++)dfs(x + xx[i], y + yy[i]);
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
cin >> a[i][j];
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
if (a[i][j] == '#') {
ans++;
dfs(i, j);
}
}
}
cout << ans;
return 0;
}
ACcode(bfs)
#include<bits/stdc++.h>
using namespace std;
int n, m;
char a[105][105];
int ans = 0;
queue<int>qx, qy;
int xx[12] = { -2,2,-1,1,0,0,0,0,1,1,-1,-1 };
int yy[12] = { 0,0,0,0,-1,1,-2,2,1,-1,-1,1 };//12个方向
void bfs() {
while (!qx.empty()) {
int ax = qx.front();int ay = qy.front();
qx.pop();qy.pop();
for (int i = 0;i < 12;i++) {
int bx = ax + xx[i];int by = ay + yy[i];
if (bx >= 1 && bx <= n && by >= 1 && by <= m && a[bx][by] == '#') {
a[bx][by] = '-';
qx.push(bx);qy.push(by);
}
}
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
cin >> a[i][j];
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
if (a[i][j] == '#') {
ans++;
qx.push(i);qy.push(j);
bfs();
}
}
}
cout << ans;
return 0;
}