解题思路:运用广度优先的搜索,从每一个感染源开始搜索,如果当前位置没有被搜索过,就标记时间。
#include<bits/stdc++.h>
#define MAX 501
using namespace std;
using gg = long long;
int n,m,a,b;
int spend_time[MAX][MAX];//时间
queue<pair<int,int> > q;//感染源队列
vector<pair<int,int> > lz;//领主的坐标
void init()
{
//将time的每一个值初始化为-1
for(int i=0;i<MAX;i++)
{
for(int j=0;j<MAX;j++)
{
spend_time[i][j]=-1;
}
}
}
void fun(int newx,int newy,int curtime)
{
//判断当前的x,y是否符合要求
if(newx>=1&&newx<=n&&newy>=1&&newy<=m&&spend_time[newx][newy]==-1)
{
//cout<<newx<<" "<<newy<<" "<<curtime<<endl;
spend_time[newx][newy]=curtime;
q.push(make_pair(newx,newy));
}
}
void bfs()
{
int cur_time = 1;
while(!q.empty())
{
int qsize = q.size();
for(int i=0;i<qsize;i++)
{
auto temp = q.front();
q.pop();
fun(temp.first-1,temp.second,cur_time);
fun(temp.first,temp.second-1,cur_time);
fun(temp.first+1,temp.second,cur_time);
fun(temp.first,temp.second+1,cur_time);
}
cur_time+=1;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m>>a>>b;
int x,y;
init();//初始化
for(int i=0;i<a;i++)
{
cin>>x>>y;
q.push(make_pair(x,y));
spend_time[x][y]=0;
}
bfs();
for(int i=0;i<b;i++)
{
cin>>x>>y;
//lz.push_back(make_pair(x,y));
cout<<spend_time[x][y]<<"\n";
}
return 0;
}