AcWing 1101. 献给阿尔吉侬的花束-BFS
原题链接
简单
作者:
hai阿卢
,
2021-03-06 13:07:58
,
所有人可见
,
阅读 325
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int,int> PII;
const int N = 210;
char a[N][N];
pair<int, int> e,f;
int n, m, d[N][N];
bool s[N][N];
queue<PII> q;
int Bfs()
{
int fx = f.first, fy = f.second;
int ex = e.first, ey = e.second;
memset(s, 0, sizeof(s));
memset(d, 0, sizeof(d));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
q.push({fx, fy});
s[fx][fy] = true;
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
for(int i = 0;i < 4; i++)
{
int xi = x + dx[i];
int yi = y + dy[i];
if(xi > 0 && xi <= n && yi > 0 && yi <= m && a[xi][yi] != '#' && !s[xi][yi])
{
q.push({xi, yi});
s[xi][yi] = true;
d[xi][yi] = d[x][y] + 1;
}
}
}
return d[ex][ey];
}
int main()
{
int t;
cin >> t;
while(t --)
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> a[i][j];
if(a[i][j] == 'S') f.first = i, f.second = j;
if(a[i][j] == 'E') e.first = i, e.second = j;
}
}
int result = Bfs();
if(!result) cout << "oop!" << endl;
else cout << result <<endl;
}
return 0;
}