尽最大能力优化了,9和10还是超时
#include <bits/stdc++.h>
using namespace std;
long long mp[3000][3000],vis[3000][3000],book[9999][9999],n,m;
struct node {int x;int y;};
queue<node> q;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int main() {
char p;
cin >> n >> m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>p;
mp[i][j]=p-'0';
}
}
for(int j=1;j<=m;j++){
long long x,y,s=1;
cin >> x >> y;
if(book[x][y] !=0 ){
cout << book[x][y] << endl;
}else{
q.push((node){x,y});
vis[x][y] = j+8888;
while(!q.empty()){
node cur = q.front();q.pop();
for(int i=0;i<4;i++){
int tx = cur.x + dx[i];
int ty = cur.y + dy[i];
if(tx>=1&&tx<=n && ty>=1&&ty<=n && vis[tx][ty]!=j+8888 && mp[cur.x][cur.y]!=mp[tx][ty]){
q.push((node){tx,ty});
vis[tx][ty]=j+8888;
s++;
}
}
}
book[x][y] = s;
cout << s << endl;
}
}
return 0;
}