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