P1332 血色先锋队
题目链接
题目思路
还是bfs题,但初始加入队列的有多个元素,所以我就没写成函数形式
题目代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
PII p[N];
int dist[N][N];
bool st[N][N];
int n, m, a, b;
int main()
{
memset(dist, -1, sizeof dist);
queue<PII> q;
cin >> n >> m >> a >> b;
for(int i = 0; i < a; i ++ )
{
int x, y;
cin >> x >> y;
q.push({x, y});
dist[x][y] = 0;
st[x][y] = true;
}
while(q.size())
{
auto t = q.front();
q.pop();
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i ++ )
{
int a = t.first + dx[i], b = t.second + dy[i];
if(a >= 1 && a <= n && b >= 1 && b <= m && !st[a][b])
{
dist[a][b] = dist[t.first][t.second] + 1;
st[a][b] = true;
q.push({a, b});
}
}
}
for(int i = 0; i < b; i ++ )
{
int l, r;
cin >> l >> r;
cout << dist[l][r] << endl;
}
return 0;
}
孤独本是常态

浙公网安备 33010602011771号