import copy
n,m = map(int,input().split())
dx = [-1,0,1,0]
dy = [0,1,0,-1]
g = []
st = [[0] * (n+10) for i in range(n+10)]
for i in range(n):
g.append(list(map(int,input())))
for i in range(m):
res = 1
tmp = copy.deepcopy(st)
a,b = map(int,input().split())
a -= 1
b -= 1
que = [(a,b)]
while que:
x,y = que.pop(0)
tmp[x][y] = 1
for j in range(4):
n_x,n_y = x + dx[j], y + dy[j]
if 0 <= n_x < n and 0 <= n_y < n and tmp[n_x][n_y] == 0:
if g[x][y] == 0 and g[n_x][n_y] == 1:
que.append((n_x,n_y))
res += 1
tmp[n_x][n_y] = 1
elif g[x][y] == 1 and g[n_x][n_y] == 0:
que.append((n_x, n_y))
res += 1
tmp[n_x][n_y] = 1
print(res)
tmp = copy.deepcopy(st)