#include<bits/stdc++.h>
using namespace std;
int n, T, ans[1010][1010], cnt, dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
char mp[1010][1010];
bool vis[1010][1010];
queue<pair<int, int> > q;
int main(){
cin >> n >> T;
for(register int i = 1;i <= n;i++){
for(register int j = 1;j <= n;j++){
//char a;
//scanf("%c", &a);
//mp[i][j] = a;
cin >> mp[i][j];
}
}
while(T--){
int a, b;
scanf("%d%d", &a, &b);
if(ans[a][b] > 0){
cout << ans[a][b] << endl;
continue;
}
memset(vis, 0, sizeof vis);
while(!q.empty()){
q.pop();
}
queue<pair<int, int> > t;
q.push(make_pair(a, b));
t.push(make_pair(a, b));
vis[a][b] = 1;
cnt = 1;
while(!q.empty()){
int x = q.front().first, y = q.front().second;
q.pop();
for(int i = 0;i < 4;i++){
int xx = x + dir[i][0], yy = y + dir[i][1];
if(!vis[xx][yy] && xx >= 1 && yy >= 1 && xx <= n && yy <= n && mp[xx][yy] != mp[x][y]){
cnt++;
q.push(make_pair(xx, yy));
t.push(make_pair(xx, yy));
vis[xx][yy] = 1;
}
}
}
while(!t.empty()){
int x = t.front().first, y = t.front().second;
ans[x][y] = cnt;
t.pop();
}
cout << ans[a][b] << endl;
}
}
结果无误,但是TLE了第二个点