#include <bits/stdc++.h>
#define PII pair<int,int>
using namespace std;
int n, mm;
char m[1001][1001];
bool f[1001][1001];
queue<PII > q;
int bfs(int x, int y)
{
int sum = 1;
q.push(make_pair(x, y));
f[x][y] = true;
while (!q.empty())
{
int xx = q.front().first, yy = q.front().second;
q.pop();
if (xx - 1 >= 1 && m[xx - 1][yy] != m[xx][yy] && !f[xx - 1][yy])
q.push(make_pair(xx - 1, yy)), sum++, f[xx - 1][yy] = true;
if (xx + 1 <= n && m[xx + 1][yy] != m[xx][yy] && !f[xx + 1][yy])
q.push(make_pair(xx + 1, yy)), sum++, f[xx + 1][yy] = true;
if (yy - 1 >= 1 && m[xx][yy - 1] != m[xx][yy] && !f[xx][yy - 1])
q.push(make_pair(xx, yy - 1)), sum++, f[xx][yy - 1] = true;
if (yy + 1 <= n && m[xx][yy + 1] != m[xx][yy] && !f[xx][yy + 1])
q.push(make_pair(xx, yy + 1)), sum++, f[xx][yy + 1] = true;
}
return sum;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> mm;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> m[i][j];
for (int i = 1; i <= mm; i++)
{
int x, y;
cin >> x >> y;
cout << bfs(x, y) << "\n";
memset(f, false, sizeof(f));
}
return 0;
}