#include <bits/stdc++.h>
#define N 1000
using namespace std;
char mmap[N][N];
int n, m, ans;
struct NODE
{
int i;
int j;
};
queue <struct NODE> q;
int BFS(struct NODE ask)
{
bool flag[N][N] = { 0 };
ans = 1;
flag[ask.i][ask.j] = 1;
struct NODE node;
q.push(ask);
while (!q.empty())
{
node = q.front();
q.pop();
if (!flag[node.i - 1][node.j] && node.i - 1 >= 0 && mmap[node.i - 1][node.j] != mmap[node.i][node.j])
{
struct NODE tmp = node;
tmp.i--;
flag[tmp.i][tmp.j] = 1;
q.push(tmp);
ans++;
}
if (!flag[node.i][node.j - 1] && node.j - 1 >= 0 && mmap[node.i][node.j - 1] != mmap[node.i][node.j])
{
struct NODE tmp = node;
tmp.j--;
flag[tmp.i][tmp.j] = 1;
q.push(tmp);
ans++;
}
if (!flag[node.i + 1][node.j] && node.i + 1 < n && mmap[node.i + 1][node.j] != mmap[node.i][node.j])
{
struct NODE tmp = node;
tmp.i++;
flag[tmp.i][tmp.j] = 1;
q.push(tmp);
ans++;
}
if (!flag[node.i][node.j + 1] && node.j + 1 < n && mmap[node.i][node.j + 1] != mmap[node.i][node.j])
{
struct NODE tmp = node;
tmp.j++;
flag[tmp.i][tmp.j] = 1;
q.push(tmp);
ans++;
}
}
return ans;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; ++i)
cin >> mmap[i];
struct NODE ask;
for (int i = 1; i <= m; ++i)
{
cin >> ask.i >> ask.j;
ask.i--;
ask.j--;
cout << BFS(ask) << endl;
}
return 0;
}