#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1005][1005];
int vis[1005][1005];
int f[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
bool check(int x, int y, int k)
{
if (x < 1 || y < 1 || x > n || y > n || vis[x][y] || a[x][y] != k ^ 1)
return false;
return true;
}
int bfs(int x, int y)
{
queue<pair<int, int>> q;
int cnt = 0;
q.push({x, y});
while (!q.empty())
{
auto it = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int xx = it.first + f[i][0];
int yy = it.second + f[i][1];
int k = a[it.first][it.second];
if (check(xx, yy, k))
{
cnt++;
vis[xx][yy] = 1;
q.push({xx,yy});
}
}
}
return cnt;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
string s;
cin >> s;
for (int j = 1; j <= n; j++)
{
a[i][j] = s[j - 1] - '0';
}
}
while (m--)
{
int x, y;
cin >> x >> y;
memset(vis, 0, sizeof(vis));
cout << bfs(x, y) << endl;
}
return 0;
}