题解
题目保证不会重置障碍,说明 * x y
的询问最多出现n*m-1次,
每次执行第二种操作就重新统计到达每个格子的最少距离,可以避免每当查询才统计答案而出现的TLE
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N=50+1;
const int INF=0x3f3f3f3f;
bool vis[N][N];
int d[N][N];
int a[N][N];
int n,m,k,dx,dy,x,y;
int dir[4][2]={1,0,0,1,0,-1,-1,0};
queue<pii>q;
void bfs(){
memset(vis, 0, sizeof(vis));
memset(d, INF, sizeof(d));
while(!q.empty())q.pop();
q.push({1,1});
d[1][1]=0;
while(!q.empty()){
pii u=q.front();
q.pop();
if(vis[u.first][u.second])continue;//诶 老是忘了这里 MLE警告
vis[u.first][u.second]=true;
for (int i = 0; i < 4; ++i) {
dx=u.first+dir[i][0];
dy=u.second+dir[i][1];
if(dx>0&&dx<=n && dy>0 && dy<=m){
if(a[dx][dy]!=1&& !vis[dx][dy]){
d[dx][dy]=min(d[dx][dy],d[u.first][u.second]+1);
q.push({dx,dy});
}
}
}
}
}
char s[2];
int main(){
ios::sync_with_stdio(0);
int T;
cin>>T;
for (int cs = 1; cs <= T; ++cs) {
memset(a, 0, sizeof(a));
cin>>n>>m>>k;
bfs();
for (int i = 1; i <= k; ++i) {
cin>>s>>x>>y;
if(s[0]=='?'){
if(d[x][y]==INF)cout <<"-1" << endl;
else cout <<d[x][y]<< endl;
}else{
a[x][y]=1;
bfs();
}
}
}
return 0;
}