#include <bits/stdc++.h>
using namespace std;
int n, m, dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, ans[1010], cnt, t[1010][1010], cnt2;
string s[1010];
bool vis[1010][1010];
void dfs(int x, int y)
{
ans[cnt] = ++cnt2;
vis[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0], ty = y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < n && !vis[tx][ty] && s[x][y] != s[tx][ty]) dfs(tx, ty);
}
}
void dfs2(int x, int y)
{
t[x][y] = ans[cnt];
vis[x][y] = 0;
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0], ty = y + dir[i][1];
if (tx >= 0 && tx < n && ty >= 0 && ty < n && vis[tx][ty] && s[x][y] != s[tx][ty]) dfs2(tx, ty);
}
}
int main ()
{
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> s[i];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!vis[i][j])
{
cnt2 = 0;
cnt++;
dfs(i, j);
}
}
}
cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (vis[i][j])
{
cnt++;
dfs2(i, j);
}
}
}
while (m--)
{
int x, y;
cin >> x >> y;
cout << t[x - 1][y - 1] << endl;
}
return 0;
}