题目链接:F-Future Vision_2021年浙大城市学院新生程序设计竞赛(同步赛) (nowcoder.com)
这题是广度优先搜索,我们可以通过搜索找到到每个点的最小距离,然后去查找出现在这个位置的最近时间,从这些时间里面求一个最小值即可
#include<bits/stdc++.h>
using namespace std;
int n, m;
char c[105][105];
bool vis[105][105];
int minn = 1000005;
int a, b;
int k;
struct node{
int x, y, step;
};
vector<int> ve[105][105];
struct cmp{
bool operator()(node a, node b){
return a.step > b.step;
}
};
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
bool check(int x, int y){
if(x >= 1 && x <= n && y >= 1 && y <= m && vis[x][y] == 0 && c[x][y] == '.'){
return true;
}else{
return false;
}
}
void bfs(){
priority_queue< node, vector<node>, cmp> q;
q.push({a, b, 0});
vis[a][b] = 1;
while(!q.empty()){
int x = q.top().x;
int y = q.top().y;
int step = q.top().step;
for(int i = 0; i < ve[x][y].size(); i++){
if(step <= ve[x][y][i]){
minn = min(ve[x][y][i], minn);
}
}
q.pop();
for(int i = 0; i < 4; i++){
int dx = x + dir[i][0];
int dy = y + dir[i][1];
if(check(dx, dy)){
vis[dx][dy] = 1;
q.push({dx, dy, step + 1});
}
}
}
}
int main(){
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int l = 1; l <= m ;l++){
cin >> c[i][l];
vis[i][l] = 0;
if(c[i][l] == 'H'){
a = i, b = l;
}
ve[i][l].clear();
}
}
cin >> k;
int x, y;
for(int i = 0; i < k; i++){
cin >> x >> y;
ve[x][y].push_back(i);
}
minn = 1000005;
bfs();
if(minn == 1000005){
cout << "NO" << endl;
}else{
cout << "YES" << " " << minn << endl;
}
}
return 0;
}