题目
cal()待修改代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
const int N = 1010;
char g1[N][N], g2[N][N];
vector<PII> land1, land2;
int n;
void get_g2()
{
for(auto c : land1)
{
for(int i = 0; i < 4; i++)
{
int nx = c.x + dx[i], ny = c.y + dy[i];
if(nx >= 0 && ny >= 0 && nx < n && ny < n && g1[nx][ny] == '.')
{
g2[c.x][c.y] = '.';
break;
}
}
}
}
int cal(char (*p)[N], vector<PII> land)
{
int mark[N][N] = {0}, cnt = 0;
for(auto c : land)
{
if(!mark[c.x][c.y]) mark[c.x][c.y] = ++cnt;
for(int i = 0; i < 4; i++)
{
int nx = c.x + dx[i], ny = c.y + dy[i];
if(nx >= 0 && ny >= 0 && nx < n && ny < n && p[nx][ny] == '#')
{
mark[nx][ny] = mark[c.x][c.y];
}
}
}
return cnt;
}
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
scanf("%s", g1[i]);
memcpy(g2, g1, sizeof g1);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
if(g1[i][j] == '#') land1.push_back({i, j});
}
get_g2();
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
if(g2[i][j] == '#') land2.push_back({i, j});
}
cout << cal(g1, land1) - cal(g2, land2);
return 0;
}
这个cal本身就很复杂。实际上cal-g的设计很傻。可以在遍历连通图的时候,同时计算bound和sum,根据这两个就可以判断计数。用二重遍历# + bfs搜索就可以了。
正确代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1010;
char g[N][N];
PII q[N * N];
int n;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool st[N][N];
void bfs(int a, int b, int& sum, int& bound)
{
int h = 0, t = 0;
q[0] = {a, b};
while(h <= t)
{
PII u = q[h++];
sum++;
bool is_bound = false;
for (int i = 0; i < 4; i ++ )
{
int nx = u.x + dx[i], ny = u.y + dy[i];
if(nx < 0 || ny < 0 || nx >= n || ny >= n || st[nx][ny]) continue;
if(g[nx][ny] == '.')
{
is_bound = true;
continue;
}
q[++t] = {nx, ny};
st[nx][ny] = true;
}
if(is_bound) bound++;
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%s", &g[i]);
int cnt = 0;
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
if(g[i][j] == '#' && !st[i][j])
{
int sum = 0, bound = 0;
bfs(i, j, sum, bound);
if(sum == bound) cnt++;
}
}
}
cout << cnt;
return 0;
}