#include <bits/stdc++.h>
using namespace std;
#define int int64_t
int n{}, m{};
enum : long long {
cwhite,
cgray,
cblack,
cbound,
csize = 1000LL + 8,
};
struct Side {
int cnt{};
};
struct Cell {
int v{};
Side* s{};
int color{ cbound };
};
Cell dd[csize][csize]{};
auto readd() -> void {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
char c; cin >> c;
dd[i][j].v = c == '1';
dd[i][j].color = cwhite;
}
}
}
struct Point {
int x{};
int y{};
};
auto iswhite(Cell* f, Point u) -> bool {
auto& d = dd[u.x][u.y];
if (d.color != cwhite) {
return false;
}
if (f) {
return f->v != d.v;
}
return true;
}
auto bfs(Point s) -> void {
if (!iswhite(0, s)) { return; }
Side* side = new Side{};
deque<Point> q;
auto push = [&q, s = side](auto p) {
q.push_back(p);
dd[p.x][p.y].color = cgray;
dd[p.x][p.y].s = s;
++s->cnt;
};
push(s);
for (; q.size(); ) {
auto u = q.front(); q.pop_front();
auto& f = dd[u.x][u.y];
for (auto v : { Point{u.x - 1,u.y},
Point{u.x + 1,u.y},
Point{u.x,u.y - 1},
Point{u.x,u.y + 1}, }) {
if (iswhite(&f, v)) {
push(v);
}
}
f.color = cblack;
}
}
auto bfs1() -> void {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
bfs({ i,j });
}
}
}
auto print() -> void {
for (int i = 1; i <= m; ++i) {
int x, y;
cin >> x >> y;
cout << dd[x][y].s->cnt << endl;
}
}
auto main() -> signed {
cin >> n >> m;
readd();
bfs1();
print();
}