bfs,o2: 128 ms
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
char g[N][N];
bool st[N][N];
int n;
int ans = 0;
int dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0};
typedef pair<int,int> PII;
void bfs(int x, int y, int &bound, int &total)
{
total++;
st[x][y] = true;
PII start = {x, y};
queue<PII> q;
q.push(start);
while(!q.empty()) {
auto tt = q.front();
q.pop();
bool is_bound = false;
for(int i = 0; i < 4; i++) {
int tx = tt.first + dx[i], ty = tt.second + dy[i];
if(tx < 0 || tx >= n || ty < 0 || ty >= n) continue;
if(st[tx][ty]) continue;
if(g[tx][ty] == '.') {
is_bound = true;
continue;
}
q.push({tx, ty});
total++;
st[tx][ty] = true;
}
if(is_bound) bound++;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for(int i = 0 ; i < n ; i++) {
cin >> g[i];
}
for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < n ; j++) {
if(!st[i][j] && g[i][j] == '#') {
int bound = 0, total = 0;
bfs(i, j, bound, total);
if(bound == total) ans++;
}
}
}
cout << ans << endl;
return 0;
}
dfs,O2:81 ms
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
char g[N][N];
bool st[N][N];
int n;
int ans = 0;
int dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0};
void dfs(int tx, int ty, int &bound, int &total)
{
st[tx][ty] = true;
bool is_bound = false;
total++;
for(int i = 0; i < 4; i++) {
int x = tx + dx[i];
int y = ty + dy[i];
if(x < 0 || x >= n || y < 0 || y >= n) continue;
if(st[x][y]) continue;
if(g[x][y] == '.') {
is_bound = true;
continue;
}
else {
dfs(x, y, bound, total);
}
}
if(is_bound) bound++;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for(int i = 0 ; i < n ; i++) {
cin >> g[i];
}
for(int i = 0 ; i < n; i++) {
for(int j = 0 ; j < n ; j++) {
if(!st[i][j] && g[i][j] == '#') {
int bound = 0, total = 0;
dfs(i, j, bound, total);
if(bound == total) ans++;
}
}
}
cout << ans << endl;
return 0;
}