队列解迷宫问题
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <climits>
#include <queue>
using namespace std;
int dx[10]= {0,-1,0,1,0},dy[10]= {0,0,-1,0,1};
int t,r,c;
char f[210][210];
int step[210][210];
int sx,sy,ex,ey;
void bfs() {
queue<pair<int,int>> q;
q.push({sx,sy});
while(q.size())
{
int x=q.front().first,y=q.front().second;
q.pop();
for(int i=1; i<=4; i++) {
int x_ne=x+dx[i],y_ne=y+dy[i];
if(x_ne>0&&x_ne<=r&&y_ne<=c&&y_ne>0&&step[x_ne][y_ne]==INT_MAX&&f[x_ne][y_ne]!='#') {
step[x_ne][y_ne]=step[x][y]+1;
q.push({x_ne,y_ne});
}
}
}
}
int main() {
cin >> t;
while(t--) {
cin >> r >> c;
for(int i=1; i<= r; i++)
for(int j=1; j<=c; j++)
cin >> f[i][j];
for(int i=1; i<=r; i++)
for(int j=1; j<=c; j++) {
step[i][j]=INT_MAX;
if(f[i][j]=='S')
sx=i,sy=j;
if(f[i][j]=='E')
ex=i,ey=j;
}
step[sx][sy]=0;
bfs();
if(step[ex][ey]!=INT_MAX) cout << step[ex][ey] << endl;
else cout << "oop!" << endl;
}
return 0;
}