很经典的一个走迷宫问题模型,总算完全靠自己写出来一次了,继续加油!
AcWing 1101 献给阿尔吉侬的花束
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int>PII;
const int N = 110;
int T;
int n, m;
char g[N][N];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int ans = 0x3f3f3f;
bool ip[N][N];
int li[N][N]; //维护距离
int main()
{
cin>>T;
while(T -- ){
ans = 0x3f3f3f;
memset(g, 0, sizeof(g));
memset(li, 0, sizeof li);
memset(ip, 0, sizeof ip);
queue<PII>q;
cin>>n>>m;
for(int i = 1; i <= n; i ++ ){
for(int j = 1; j <= m; j ++ ){
cin>>g[i][j];
if(g[i][j] == 'S'){
q.push({i, j});
li[i][j] = 0;
}
}
}
while(!q.empty()){
auto op = q.front();
q.pop();
int x1 = op.x, y1 = op.y;
for(int i = 0; i < 4; i ++ ){
int xx = x1 + dx[i];
int yy = y1 + dy[i];
if(xx >= 1 && yy >= 1 && xx <= n && yy <= m && g[xx][yy] != '#' && !ip[xx][yy]){
li[xx][yy] = li[x1][y1] + 1;
q.push({xx, yy});
ip[xx][yy] = true;
if(g[xx][yy] == 'E'){
ans = min(ans, li[xx][yy]);
}
}
}
}
if(ans > 40000) cout<<"oop!"<<endl;
else cout<<ans<<endl;
}
return 0;
}