#include <bits/stdc++.h>
using namespace std;
bool visit[1005][1005];
char s[1005][1005];
int ans = 0;
int n, m, x, y;
queue<pair<int, int> > q;
bool fact(int xx, int yy) {
if (xx<1 || xx>n || yy<1 || yy>n || visit[xx][yy]) return false;
return true;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> s[i][j];
}
}
for (int i = 0; i < m; i++) {
ans = 1;
cin >> x >> y;
q.push(make_pair(x, y));
memset(visit, false, sizeof(visit));
visit[x][y] = true;
while (!q.empty()) {
int x_now = q.front().first;
int y_now = q.front().second;
q.pop();
if (s[x_now][y_now] + s[x_now - 1][y_now] - 2 * '0' == 1) {
int xx = x_now - 1;
int yy = y_now;
if (fact(xx, yy)) {
visit[xx][yy] = true;
ans++;
q.push(make_pair(xx, yy));
}
}
if (s[x_now][y_now] + s[x_now + 1][y_now] - 2 * '0' == 1) {
int xx = x_now + 1;
int yy = y_now;
if (fact(xx, yy)) {
visit[xx][yy] = true;
ans++;
q.push(make_pair(xx, yy));
}
}
if (s[x_now][y_now] + s[x_now][y_now + 1] - 2 * '0' == 1) {
int xx = x_now;
int yy = y_now + 1;
if (fact(xx, yy)) {
visit[xx][yy] = true;
ans++;
q.push(make_pair(xx, yy));
}
}
if (s[x_now][y_now] + s[x_now][y_now - 1] - 2 * '0' == 1) {
int xx = x_now;
int yy = y_now - 1;
if (fact(xx, yy)) {
visit[xx][yy] = true;
ans++;
q.push(make_pair(xx, yy));
}
}
}
cout << ans << endl;
}
return 0;
}