经典bfs,不过翻译过来题意要读顺,思路是将有加湿器的的地板同时放入队列,分别向各个方向移动加湿器,用dis数组记录每个地板为多少步移动到的(即地板与加湿器的距离), dis数组初始化为无穷大,以便记录对应空地板与最近加湿器的距离,最后遍历检测dis数组,在限定距离d内即为加湿器可以加湿到。
(主要记录代码结构,比最开始一版效率优化很多)
#include <cstring>
#include <iostream>
#include <queue>
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0), cout.tie(0);
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
string s[N];
int h, w, d, ans, dis[N][N], dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
queue<PII> q;
signed main()
{
IOS
cin >> h >> w >> d;
memset(dis, 0x3f, sizeof dis);
for (int i = 0; i < h; i++)
{
cin >> s[i];
for (int j = 0; j < w; j++)
if (s[i][j] == 'H')
{
dis[i][j] = 0;
q.push({i, j});
}
}
while (q.size())
{
int x = q.front().first, y = q.front().second;
q.pop();
for (int k = 0; k < 4; k++)
{
int tx = x + dx[k], ty = y + dy[k];
if (tx >= 0 && tx < w && ty >= 0 && ty < h && s[tx][ty] == '.' && dis[tx][ty] > dis[x][y] + 1)
{
dis[tx][ty] = dis[x][y] + 1;
q.push({tx, ty});
}
}
}
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
ans += (dis[i][j] <= d);
cout << ans << endl;
}
286

被折叠的 条评论
为什么被折叠?



