#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#define x first
#define y second
using namespace std;
const int N = 210;
typedef pair<int,int> PII;
int n,m;
char g[N][N];
int dist[N][N];//将判重数组和距离合二为一
int bfs(PII start,PII end)//都为PII型
{
queue<PII> q;
memset(dist,-1,sizeof dist);//初始化距离数组为-1
dist[start.x][start.y] = 0;//起点的距离为0
q.push(start);//起点入队
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};//偏移量数组
while(q.size())//当队非空
{
PII t = q.front();
q.pop();//弹出队头
for(int i = 0;i < 4;i++)
{
int a = t.x + dx[i],b = t.y + dy[i];
if(a < 0 || a >= n || b < 0 || b >= m) continue;//出界
if(g[a][b] == '#') continue;//撞墙
if(dist[a][b] != -1) continue; //判重
dist[a][b] = dist[t.x][t.y] + 1;//否则距离加一
if(end == make_pair(a,b)) return dist[a][b];//返回距离值
q.push({a,b});//入队
}
}
return -1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i = 0;i < n;i++) scanf("%s",g[i]);
PII start,end;
for(int i = 0;i < n;i++)
{
for(int j = 0;j < m;j++)
{
if(g[i][j] == 'S')
{
start = {i,j};
}
else if(g[i][j] == 'E')
{
end = {i,j};
}
}
}
int distance = bfs(start,end);
if(distance == -1)
{
puts("oop!");
}
else
{
printf("%d\n", distance);
}
}
return 0;
}