import java.io.*;
import java.util.*;
public class Main {
static int[] orient = {0, 1, 0, -1, 0};
static boolean[][] vis;
public static void main(String[] args) {
myScanner sc = new myScanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] x = new char[n][];
for (int i = 0; i < n; i++) {
x[i] = sc.next().toCharArray();
}
int[][] res = new int[n][n];
Queue<int[]> queue = new LinkedList<>();
Queue<int[]> queue2 = new LinkedList<>();
vis = new boolean[n][n];
for (int k = 0; k < n; k++) {
for (int p = 0; p < n; p++) {
if (!vis[k][p]) {
vis[k][p] = true;
queue.add(new int[]{k, p});
queue2.add(new int[]{k, p});
int sum = 0;
while (!queue.isEmpty()) {
sum++;
int[] loc = queue.poll();
for (int l = 0; l < 4; l++) {
int i = loc[0] + orient[l];
int j = loc[1] + orient[l + 1];
if (i < 0 || j < 0 || i >= x.length || j >= x.length || vis[i][j] || x[loc[0]][loc[1]] == x[i][j])
continue;
vis[i][j] = true;
queue.offer(new int[]{i, j});
queue2.offer(new int[]{i, j});
}
}
while (!queue2.isEmpty()) {
int[] loc = queue2.poll();
res[loc[0]][loc[1]] = sum;
}
}
}
}
while (m-- > 0) {
int i = sc.nextInt()-1;
int j = sc.nextInt()-1;
System.out.println(res[i][j]);
}
}
static class myScanner {
public BufferedReader reader;
public StringTokenizer st;
myScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
st = null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
}
}
洛谷 P1141 01迷宫 Java
最新推荐文章于 2024-05-30 16:17:47 发布