1101. 献给阿尔吉侬的花束
BFS 终于有一个轻松的了!!!!
//BFS
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 210;
int r,c;
int vis[N][N];
char a[N][N];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
struct nod
{
int x,y;
int step;
}node[N*N];
int bfs(int x0,int y0,int xe,int ye)
{
int res =0;
queue<nod> q;
q.push({x0,y0,0});
vis[x0][y0] = 1;
while(!q.empty())
{
nod top = q.front();
q.pop();
if(top.x == xe && top.y ==ye)
{
return top.step;
}
for(int i=0;i<4;i++)
{
int x = top.x + dx[i];
int y = top.y + dy[i];
if(x>=1 && x<=r && y>=1 && y<=c && !vis[x][y] && a[x][y] != '#')
{
vis[x][y] = 1;
q.push({x,y,top.step+1});
}
}
}
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(vis,0,sizeof vis);
memset(a,0,sizeof a);
cin>>r>>c;
int x0,y0,xe,ye;
for(int i=1;i<=r;i++)
{
for(int j=1;j<=c;j++)
{
cin>>a[i][j];
if(a[i][j] == 'S') {x0 = i,y0 = j;}
if(a[i][j] == 'E') {xe = i,ye = j;}
}
// getchar(); scanf
}
int res = bfs(x0,y0,xe,ye);
if(res!= -1)
{
printf("%d\n",res);
}
else puts("oop!");
}
}