DauntlessHSM @ 2024-03-28 10:39:27
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class P1141 {
public static int[][] maze, connected;
public static int n, m, count;
public static int[] color;
public static class Pair {
int x;
int y;
public Pair(int xi, int yi) {
x = xi;
y = yi;
}
}
public static boolean check(int x, int y, int code) {
return x >= 0 && x < n && y >= 0 && y < n && maze[x][y] == code && connected[x][y] == 0;
}
public static void bfs(int x, int y) {
int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Queue<Pair> queue = new ArrayDeque<>();
queue.offer(new Pair(x, y));
connected[x][y] = count;
color[count] += 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i += 1) {
Pair cur = queue.poll();
int code = maze[cur.x][cur.y] == 0 ? 1 : 0;
for (int j = 0; j < 4; j += 1) {
int newX = cur.x + dir[j][0];
int newY = cur.y + dir[j][1];
if (check(newX, newY, code)) {
queue.offer(new Pair(newX, newY));
connected[newX][newY] = count;
color[count] += 1;
}
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
color = new int[n * n + 1];
maze = new int[n][n];
connected = new int[n][n];
for (int i = 0; i < n; i += 1) {
String temp = in.next();
for (int j = 0; j < n; j += 1) {
maze[i][j] = temp.charAt(j) - '0';
}
}
count = 1;
for (int i = 0; i < n; i += 1) {
for (int j = 0; j < n; j += 1) {
if (connected[i][j] == 0) {
bfs(i, j);
count += 1;
}
}
}
for (int i = 0; i < m; i += 1) {
int x = in.nextInt() - 1, y = in.nextInt() - 1;
System.out.println(color[connected[x][y]]);
}
}
}