#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
//typedef pair<int, int> PII;
const int N = 210;
char a[N][N];
int dis[N][N];
struct hw
{
int first,second;
}oi;
void bfs(hw start)
{
queue<hw> q;
q.push(start);//队头队,对应步骤1
while(!q.empty())
{
hw u = q.front();
q.pop();
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0 ,-1};
for(int i = 0; i < 4; i++)//遍历四个方向,对应步骤2
{
int x = u.first + dx[i];
int y = u.second + dy[i];
if(a[x][y] == '#') continue;//如果是'#',不做任何处理
if(a[x][y] == '.')//如果是 '.',更新对应内容
{
dis[x][y] = dis[u.first][u.second] + 1;
a[x][y] = '#';
oi.first=x,oi.second=y;
q.push(oi);
}
if(a[x][y] == 'E')//如果是'E',找到了,输出
{
cout << dis[u.first][u.second] + 1 << endl;
return;
}
}
}
cout << "oop!" << endl;//没有找到
}
int main()
{
int t;
cin >> t;
while(t--)
{
memset(a, '#', sizeof(a));//初始化地图,各个点都是墙。
memset(dis, 0, sizeof(dis));//初始化dis
int n,m;
hw start;
cin >> n >> m;
for(int i = 1; i <= n; i++)//从第一行存储地图,因为四周都是墙,bfs时,可以不做越界判断
{
for(int j = 1; j <= m; j++)//从第一;列存储地图,因为四周都是墙,bfs时,可以不做越界判断
{
cin >> a[i][j];
if(a[i][j] == 'S')//记录下起点位置。
start.first = i, start.second = j, a[i][j] = '#';
}
}
bfs(start);
}
}
AcWing 1101. 献给阿尔吉侬的花束(bfs)
最新推荐文章于 2025-03-18 15:41:28 发布