#include<iostream>
#include<queue>
#include<cstring>
//#define x first ;
//#define y second ;
using namespace std;
int n;
int w, h;
typedef pair<int, int> PII;
char map[210][210];
int dist[210][210];
int direct[4][2] = { {1,0 },{0,1},{-1,0},{0,-1} };
bool in(int xx, int yy) {
return xx >= 0 && xx < w&& yy >= 0 && yy < h;
}
int bfs(PII start, PII end) {
queue<PII>q;
memset(dist, -1, sizeof(dist));
dist[start.first][start.second] = 0;
q.push(start);
while (q.size()) {
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int x1 = t.first + direct[i][0];
int y1 = t.second + direct[i][1];
if (in(x1, y1) && map[x1][y1] != '#' && dist[x1][y1] == -1) {
dist[x1][y1] = dist[t.first][t.second] + 1;
if (end.first==x1&&end.second==y1) {
return dist[x1][y1];
}
q.push({ x1, y1 });
}
}
}
return -1;
}
int main() {
scanf("%d", &n);
PII start = { 0,0 };
PII end = { 0,0 };
while (n--) {
scanf("%d%d",&w,&h);
for (int i = 0; i < w; i++) {
for(int j=0;j<h;j++){
cin>>map[i][j];
if (map[i][j] == 'S') {
start = { i,j };
}
if (map[i][j] == 'E') {
end = { i,j };
}
}
}
int dis = bfs(start, end);
if (dis == -1) {
puts("oop!");
}
else {
printf("%d\n", dist[end.first][end.second]);
}
}
return 0;
}