#include <iostream>
#include <queue>
using namespace std;
int maze[1005][1005] = {0};
int used[1005][1005] = {0};
int dcol[] = {0, 1, 0, -1};
int drow[] = {-1, 0, 1, 0};
int main() {
int n, m;
cin >> n >> m;
for (int row = 0; row < n; ++row) {
string temp;
cin >> temp;
int index = 0;
for (auto col: temp) {
maze[row][index] = col - '0';
++index;
}
}
for (int t = 0; t < m; ++t) {
int start_row, start_col;
cin >> start_row >> start_col;
--start_row;
--start_col;
int count = 0;
queue<int> q;
q.push(start_row);
q.push(start_col);
while (!q.empty()) {
int row = q.front();
q.pop();
int col = q.front();
q.pop();
if (used[row][col]) continue;
else used[row][col] = 1;
++count;
for (int i = 0; i < 4; ++i) {
int new_row = row+drow[i];
int new_col = col+dcol[i];
if (new_row < 0 || new_col < 0 || new_row >= n || new_col >= n) {
continue;
}
if (maze[new_row][new_col] != maze[row][col]) {
q.push(new_row);
q.push(new_col);
}
}
}
cout << count << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
used[i][j] = 0;
}
}
}
}
[https://www.luogu.com.cn/record/78541706]