your_bug_fired @ 2024-11-04 18:01:09
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
int check[1010][1010] = {0};
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int n = 0;
int a[1010][1010] = {0};
char a_[1010][1010] = {};
int answer[1010][1010] = {0};
void bfs(pii p){
int ans = 0;
queue <pii> q;
vector <pii> ve;
if(answer[p.first][p.second]){
return;
}
q.push(p);
ve.push_back(p);
check[p.first][p.second] = 1;
while(!q.empty()){
pii top = q.front();
for(int i = 0; i < 4; i++){
if(top.first + dx[i] > 0 && top.first + dx[i] <= n && top.second + dy[i] > 0 && top.second + dy[i] <= n && check[top.first + dx[i]][top.second + dy[i]] == 0 && a[top.first][top.second] ^ a[top.first + dx[i]][top.second + dy[i]]){
check[top.first + dx[i]][top.second + dy[i]] = 1;
q.push({top.first + dx[i], top.second + dy[i]});
ve.push_back({top.first + dx[i], top.second + dy[i]});
}
}
q.pop();
ans++;
for(auto l : ve){
answer[l.first][l.second] = ans;
}
}
}
int main(){
int m = 0;
cin>>n>>m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin>>a_[i][j];
if(a_[i][j] == '1') a[i][j] = 1;
}
}
while(m--){
int x = 0, y = 0;
cin>>x>>y;
bfs({x, y});
printf("%d\n", answer[x][y]);
}
return 0;
}