d=[[1,0],[0,1],[-1,0],[0,-1]]
def bfs(x,y):
visited[x][y]=True
queue=[(x,y)]
cnt=1
while queue:
for i in range(len(queue)):
x,y=queue.pop(0)
for dx,dy in d:
tx=x+dx
ty=y+dy
if 0<=tx<n and 0<=ty<n and visited[tx][ty]==False and l[tx][ty]!=l[x][y]:
visited[tx][ty]=True
queue.append((tx,ty))
cnt+=1
return cnt
n,m=map(int,input().split())
l=[[0 for i in range(n)]for j in range(n)]
for i in range(n):
x=list(map(int,input()))
l[i]=x
while m:
a,b=map(int,input().split())
print(bfs(a-1,b-1))
visited=[[False for i in range(n)]for j in range(n)]
m-=1