bfs,但是有點巧妙?還是自己沒理解好原本的題,沒轉換好
解題思路:
- 就是常規的bfs,只不過處理點的時候有點技巧
- (應該也不算技巧)只是讓原本要出發點的dist值爲0,然後存入隊列中,然後排着去搜索就OK
- 還是挺簡單的,可能想的有點慢
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
const int N = 510;
int dist[N][N];
int idx[4] = {0,0,1,-1};
int idy[4] = {1,-1,0,0};
int n, m;
queue<PII> q;
void bfs(){
while(!q.empty()){
PII t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; i ++){
int xx = x + idx[i];
int yy = y + idy[i];
if (xx >= 1 && xx <= n && yy <= m && yy >= 1 && dist[xx][yy] == -1){
dist[xx][yy] = dist[x][y] + 1;
q.push({xx,yy});
}
}
}
}
int main(){
int a, b;
memset(dist,-1,sizeof dist);
scanf("%d%d%d%d",&n,&m,&a,&b);
for (int i = 0; i < a; i++){
int x, y;
scanf("%d%d",&x,&y);
dist[x][y] = 0;
q.push({x,y});
}
bfs();
for (int i = 0; i < b; i++){
int x, y;
scanf("%d%d",&x,&y);
printf("%d\n", dist[x][y]);
}
return 0;
}