import java.awt.*;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static int m,n,k=1;
public static int[] dx = {-1,0,1,0};
public static int[] dy = {0,1,0,-1};
public static char[][] arr = new char[1004][1004];
public static int[][] book = new int[1004][1004];
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
m = scan.nextInt();
int[] xx = new int[m];
int[] yy = new int[m];
int[] sum = new int[m+1];
int[] num = new int[m];
for(int i = 1;i<=n;i++){
String str = scan.next();
for(int j = 1;j<=n;j++){
arr[i][j] = str.charAt(j-1);
}
}
for(int i = 0; i < m; ++i) {
xx[i] = scan.nextInt();
yy[i] = scan.nextInt();
}
for(int i = 0;i < m; ++i) {
if(book[xx[i]][yy[i]]==0){
sum[k] = bfs(xx[i], yy[i]);
num[i] = sum[k];
k++;
}else{
num[i] = sum[book[xx[i]][yy[i]]];
}
}
for(int i =0;i< m; ++i){
System.out.println(num[i]);
}
}
public static int bfs(int x, int y) {
int count=1;
Point p = new Point(x,y);
LinkedList<Point> queue = new LinkedList<Point>();
queue.add(p);
book[x][y] = k;
while(!queue.isEmpty()){
Point first = queue.removeFirst();
for(int i = 0; i < 4; ++i) {
int nx = first.x + dx[i];
int ny = first.y + dy[i];
if(nx>=1&&nx<=n&&ny>=1&&ny<=n&&book[nx][ny]==0&&((arr[first.x][first.y]=='0'
&&arr[nx][ny]=='1')||(arr[first.x][first.y]=='1'&&arr[nx][ny]=='0'))){
count++;
book[nx][ny] = k;
queue.add(new Point(nx,ny));
}
}
}
return count;
}
}