#include<bits/stdc++.h>
using namespace std;
int n, m;
bool vis[1001][1001], v[1001][1001];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
struct node
{
int x, y;
};
void bfs(int x, int y)
{
queue<node>q;
q.push({x, y});
int sum = 1;
while (!q.empty())
{
node u = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int xx = dx[i] + u.x;
int yy = dy[i] + u.y;
if (xx > 0 && yy > 0 && xx <= n && yy <= n && vis[u.x][u.y] != vis[xx][yy] && !v[xx][yy])
{
sum++;
q.push({xx, yy});
v[xx][yy] = 1;
}
}
}
printf("%d\n", sum);
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
char c;
cin >> c;
if (c == '1') vis[i][j] = 1;
else vis[i][j] = 0;
}
}
while (m--)
{
memset(v, 0, sizeof(v));
int x, y;
scanf("%d%d", &x, &y);
v[x][y] = 1;
bfs(x, y);
}
return 0;
}