andy22 @ 2024-07-19 20:21:19
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
char mp[N][N];
bool visit[N][N];
int n, m;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
bool check(int x, int y){
return (x >= 0 && x < n && y >= 0 && y < n);
}
int bfs(int x, int y) {
int ans = 1;
visit[x][y] = 1;
queue<pair<int,int>> que;
que.push({x, y});
while(!que.empty()){
x = que.front().first;
y = que.front().second;
que.pop();
// cout << ans;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(check(nx,ny) && !visit[nx][ny] && mp[x][y] != mp[nx][ny]) {
ans++;
// cout << nx << " " << ny << endl;
visit[nx][ny] = 1;
que.push({nx,ny});
}
}
}
return ans;
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++) {
scanf("%s", &mp[i]);
}
int x, y;
for(int i = 1; i <= m; i++) {
scanf("%d %d", &x, &y);
memset(visit, 0, sizeof(visit));
printf("%d\n", bfs(x, y));
}
return 0;
}
by han1219 @ 2024-07-19 20:52:30
先开long long试试
by ATION001 @ 2024-07-19 20:55:29
@andy22 温馨提示:本题用普通思想会超时,要预处理。
#include<bits/stdc++.h>
using namespace std;
using pii=pair<int,int>;
int _x[4]={0,0,-1,1},_y[4]={-1,1,0,0};
int b[1005][1005],sum[100010];
char a[1005][1005];
int n,m;
void bfs(int x,int y,int flag){
queue<pii>q;
q.push({x,y});
sum[flag]++,b[x][y]=flag;
while(q.size()){
pii p=q.front();
q.pop();
for(int i=0;i<4;i++){
int dx=p.first+_x[i],dy=p.second+_y[i];
if(a[dx][dy]=='o'||b[dx][dy]!=-1||a[p.first][p.second]==a[dx][dy]){
continue;
}
sum[flag]++,b[dx][dy]=flag;
q.push({dx,dy});
}
}
}
int main(){
fill(a[0],a[1005],'o');
fill(b[0],b[1005],-1);
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
}
}
for(int i=1,x,y;i<=m;i++){
cin>>x>>y;
if(b[x][y]==-1){
bfs(x,y,i);
}else{
sum[i]=sum[b[x][y]];
}
}
for(int i=1;i<=m;i++){
cout<<sum[i]<<endl;
}
return 0;
}
求关。
by ATION001 @ 2024-07-19 21:33:15
把地图当做连通块预处理。