sunxiaochuan152 @ 2024-12-21 16:58:23
#visited=[0 for i in range(n)for j in range(n)]
#path=[[(-1,-1)for i in range(n)]for j in range(n)]
#l=[0 for i in range(n)]for j in range(n)]
d=[[1,0],[0,1],[-1,0],[0,-1]]
#cnt=1
def bfs(x,y):
#visited=[[False for i in range(n)]for j in range(n)]
visited[x][y]=True
queue=[(x,y)]
cnt=1
while queue:
for i in range(len(queue)):
x,y=queue.pop(0)
#cnt+=1
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())
#path=[[(-1,-1)for i in range(n)]for j in range(n)]
l=[[0 for i in range(n)]for j in range(n)]
#visited=[[0 for i in range(n+2)]for j in range(n+2)]
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