#include <bits/stdc++.h>
using namespace std;
int n, m;
char c[1001][1001];
int ans[100001];
bool b[1001][1001];
int f[1001][1001];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void dfs(int x, int y, bool f, int l)
{
if (x < 1 || y < 1 || x > n || y > n || b[x][y] == true || c[x][y] - '0' != f)
{
return;
}
ans[l]++;
f = !f;
b[x][y] = true;
dfs(x - 1, y, f, l);
dfs(x + 1, y, f, l);
dfs(x, y + 1, f, l);
dfs(x, y - 1, f, l);
}
int main ()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> c[i][j];
}
}
memset(f, -1, sizeof(f));
for (int i = 1; i <= m; i++)
{
memset(b, false, sizeof(b));
int x, y;
cin >> x >> y;
if (f[x][y] == -1)
{
dfs(x, y, c[x][y] - '0', i);
f[x][y] = ans[i];
}
cout << f[x][y] << endl;
}
return 0;
}
大佬救命!!!