#3和#11TLE,求助
#include <bits/stdc++.h>
using namespace std;
int n, m, startx, starty;
int a[1005][1005];
int b[1005][1005];
int step[1005][1005];
int vis[1005][1005];
struct point {
int x;
int y;
};
queue<point> r;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
char ch;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> ch;
if (ch == '1')
a[i][j] = 1;
else
a[i][j] = 0;
}
}
for (int i = 0; i <= n + 1; i++) {
a[i][0] = 2;
b[i][0] = 2;
vis[i][0] = 2;
a[i][n + 1] = 2;
b[i][n + 1] = 2;
vis[i][n + 1] = 2;
}
for (int i = 0; i <= n + 1; i++) {
a[0][i] = 2;
b[0][i] = 2;
vis[0][i] = 2;
a[n + 1][i] = 2;
b[n + 1][i] = 2;
vis[n + 1][i] = 2;
}
while (m--) {
// memset(vis, 0, sizeof(int));
int tstep = 1;
cin >> startx >> starty;
//bfs
if (b[startx][starty] == 0) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
vis[i][j] = 0;
}
}
point start;
start.x = startx;
start.y = starty;
r.push(start);
b[startx][starty] = 2;
vis[startx][starty] = 2;
while (!r.empty()) {
int x = r.front().x, y = r.front().y;
for (int i = 0; i <= 3; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (a[x][y] == 1 && a[tx][ty] == 0 && vis[tx][ty] != 2) {
point temp;
temp.x = tx;
temp.y = ty;
tstep++;
r.push(temp);
b[tx][ty] = 2;
vis[tx][ty] = 2;
} else if (a[x][y] == 0 && a[tx][ty] == 1 && vis[tx][ty] != 2) {
point temp;
temp.x = tx;
temp.y = ty;
tstep++;
r.push(temp);
b[tx][ty] = 2;
vis[tx][ty] = 2;
}
}
r.pop();
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
// cout << vis[i][j];
if (vis[i][j] == 2 && tstep > step[i][j]) {
step[i][j] = tstep;
}
}
}
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= n; j++) {
// cout << vis[i][j];
// }
// cout << endl;
// }
cout << tstep << endl;
} else {
cout << step[startx][starty] << endl;
// for (int i = 1; i <= n; i++) {
// for (int j = 1; j <= n; j++) {
// cout << vis[i][j];
// }
// cout << endl;
// }
}
}
return 0;
}