源代码:
#include <bits/stdc++.h>
using namespace std;
queue <int> x;
queue <int> y;
int n,m,aa,b,xx,yy,ans[10005],a[505][505];
int pd[505][505];
int xfx[5]= {0,1,-1,0,0};
int yfx[5]= {0,0,0,1,-1};
int main() {
cin>>n>>m>>aa>>b;
for(int i=1; i<=aa; i++) {
cin>>xx>>yy;
x.push(xx);
y.push(yy);
pd[xx][yy]=-1;
}
for(int i=1; i<=b; i++) {
cin>>xx>>yy;
pd[xx][yy]=i;
}
while(!x.empty()) {
for(int i=1; i<=4; i++) {
int lsx=x.front()+xfx[i];
int lsy=y.front()+yfx[i];
if(lsx>=1&&lsx<=n&&lsy>=1&&lsy<=m&&pd[lsx][lsy]!=-1) {
x.push(lsx);
y.push(lsy);
a[lsx][lsy]=a[x.front()][y.front()]+1;
if(pd[lsx][lsy]>=1) {
ans[pd[lsx][lsy]]=a[lsx][lsy];
}
pd[lsx][lsy]=-1;
}
}
x.pop();
y.pop();
}
for(int i=1; i<=b; i++) {
cout<<ans[i]<<endl;
}
// for(int i=1; i<=n; i++) {
// for(int j=1; j<=m; j++) {
// cout<<a[i][j]<<" ";
// }
// cout<<endl;
// }
return 0;
}