yandi_ @ 2024-08-09 17:55:05
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
int n;
int m;
int dp[1001][1001];
int migong[1001][1001];
struct node{
int x,y;
node operator+ (const node S)const{
node ans={x+S.x,y+S.y};
return ans;
}
};
node fangxiang[5]={{0,0},{0,-1},{0,1},{1,0},{-1,0}};
int bfs(int x,int y){
queue<node> q;
queue<node> ue;
q.push({x,y});
int ans=0;
bool went[n+1][n+1]={};
while(!q.empty()){
node now=q.front();
q.pop();
ue.push(now);
for(int i=1;i<=4;i++){
node will=now+fangxiang[i];
if(will.x>0 && will.x<=n && will.y>0 && will.y<=n && migong[will.x][will.y]==!migong[now.x][now.y] && !went[will.x][will.y]){
ans++;
q.push(will);
went[will.x][will.y]=1;
}
}
}
//cout<<ans<<endl;
while(ue.size()){
node now1=ue.front();
ue.pop();
dp[now1.x][now1.y]=ans;
}
return dp[x][y];
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%1d",&migong[i][j]);
}
}
for(int i=1;i<=m;i++){
int a,b;
cin>>a>>b;
if(dp[a][b]){
cout<<dp[a][b]<<endl;
continue;
}
cout<<bfs(a,b)<<endl;
}
return 0;
}
by Causality_ @ 2024-08-16 11:32:40
@yandi_ 数组调大一点,读取迷宫之后直接bfs全部,询问的时候就直接调用
by yandi_ @ 2024-08-16 16:02:41
@Causality_ 谢谢