就是一个保存一下每个到点的时间即可
需要注意的是输入的区别,这里列一下 cin / scanf 读到空格时的区别
cin 读到空格停止,但会读掉空格
scanf 读到空格也会停止,但不会读掉空格(也就是说还有空格没有读)
并且在这道题中小 A 和小 B 的 BFS 大体一样,故可用写一个函数,记录 id 的方式简洁写出代码
挑战此题最短代码(我会写空格233)
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
int nex[3][10] = {{0,-1,0,1,0},{0,-1,-1,0,1,1,1,0,-1}},ney[3][10] = {{0,0,1,0,-1},{0,0,1,1,1,0,-1,-1,-1}};
int vis[3][1001][1001];
int n,m;
int can[1001][1001];
int bex[3],bey[3];
queue<pair<int,int> > p;
inline void bfs(int id) {
vis[id][bex[id]][bey[id]] = 1;
p.push(mp(bex[id],bey[id]));
while(p.empty() == false) {
pair<int,int> pos = p.front();
p.pop();
for(int i = 1;i <= id * 4;i++) {
int X = pos.first + nex[id - 1][i],Y = pos.second + ney[id - 1][i];
if((X >= 1 && X <= n) && (Y >= 1 && Y <= m) && can[X][Y] == 0 && vis[id][X][Y] == 0) {
vis[id][X][Y] = vis[id][pos.first][pos.second] + 1;
p.push(mp(X,Y));
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n >> m ;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= m;j++) {
char x;
cin >> x;
if(x == '#') can[i][j] = 1;
if(x == 'C') bex[2] = i,bey[2] = j;
if(x == 'D') bex[1] = i,bey[1] = j;
}
}
bfs(2);
bfs(1);
int ans = 2e9;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <= m;j++) {
if(!can[i][j] && vis[1][i][j] != 0)
ans = min(ans,max(vis[1][i][j] / 2,vis[2][i][j] - 1));
}
}
if(ans != 2e9) {
cout << "YES" << '\n';
cout << ans << '\n';
}
else {
cout << "NO" << '\n';
}
return 0;
}

京公网安备 11010502036488号