#include <bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i = (a);i<=(b);i++)
#define per(i,a,b) for(int i = (a);i>=(b);i--)
typedef std::pair<int, int> PII;
#define scanf scanf_s
using namespace std;
const int N = 1010;
int m, n, ans = 1;
char a[N][N];
bool used[N][N];
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
int bfs(int x, int y)
{
used[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (!used[nx][ny] and a[nx][ny] != a[x][y] and nx>0 and nx<=n and ny>0 and ny<=n) {
bfs(nx, ny);
ans++;
}
}
return ans;
}
inline void solved()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
}
}
while (m--) {
ans = 1;
memset(used, false, sizeof used);
int x, y;
cin >> x >> y;
cout << bfs(x, y) << endl;
}
}
signed main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int T = 1;
while (T--) solved();
return 0;
}