今天浅浅复习巩固一下bfs

答案:

#include#include#includeusing namespace std;typedef pair PII;const int N=510; int n,m,a,b;int dist[N][N];PII q[N*N];int hh=0,tt=-1;int dx[]={1,0,-1,0};int dy[]={0,1,0,-1};void bfs(){while(hh<=tt){PII t=q[hh++];for(int i=0;i<4;i++){int a=t.first+dx[i];int b=t.second+dy[i];if(an||bm) continue;if(dist[a][b]>=0) continue;dist[a][b]=dist[t.first][t.second]+1;q[++tt]={a,b};}}}int main(){scanf("%d %d %d %d",&n,&m,&a,&b);memset(dist,-1,sizeof dist);while(a--){int x,y;scanf("%d %d",&x,&y);//q[tt++]={x,y};q[++tt]={x,y};dist[x][y]=0;}bfs();while(b--){int x,y;scanf("%d %d",&x,&y);printf("%d\n",dist[x][y]);}return 0; }