yaokuangda @ 2024-03-24 23:46:32
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
char loc[N][N];
int n, m, ans, cou, res[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
bool st[N][N];
struct tem {int x1, y1;} temp[100010];
void dfs(int x, int y) {
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 1 || a > n || b < 1 || b > n) continue;
if (st[a][b]) continue;
if (loc[a][b] == loc[x][y]) continue;
st[a][b] = true;
ans++;
cou++;
temp[cou].x1 = a, temp[cou].y1 = b;
dfs(a, b);
}
}
int main() {
cin >> n >> m;
int x=0,y=0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cin >> loc[i][j];
}
memset(res, 0, sizeof(res));
for (int i = 1; i <= m; i++) {
cin >> x >> y;
if (res[x][y]) {
cout << res[x][y] << endl;
} else {
ans = 1; cou = 0;
memset(st, false, sizeof(st)); // 重置 st 数组
st[x][y] = true;
dfs(x, y);
temp[0].x1 = x, temp[0].y1 = y;
for (int j = 0; j <= cou; j++) {
res[temp[j].x1][temp[j].y1] = ans;
}
cout << res[x][y] << endl;
}
}
return 0;
}