import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int m,n;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
for(int ii=0;ii<x;ii++){
m = in.nextInt();
n = in.nextInt();
Node3 s = new Node3();
Node3 e = new Node3();
char[][] maze = new char[m][n];
for(int i=0;i<m;i++){
String str = in.next();
for(int j=0;j<n;j++){
maze[i][j] = str.charAt(j);
if(maze[i][j]=='S'){
s.x=i;
s.y=j;
}
else if(maze[i][j]=='E'){
e.x=i;
e.y=j;
}
}
}
System.out.println(bfs(maze,s,e));
}
}
public static int bfs(char[][] maze, Node3 s, Node3 e) {
int[][] d = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
Queue<Node3> q = new LinkedList<Node3>();
q.add(s);
maze[s.x][s.y] = '@';
while (!q.isEmpty()) {
Node3 t = q.poll();
for (int i = 0; i < 4; i++) {
int xx = t.x + d[i][0];
int yy = t.y + d[i][1];
if (xx == e.x && yy == e.y){
return t.d+1;
}
}
for (int i = 0; i < 4; i++) {
int xx = t.x + d[i][0];
int yy = t.y + d[i][1];
if (xx >= 0 && xx < m && yy >= 0 && yy < n
&& maze[xx][yy] == '-') {
maze[xx][yy] = '@';
q.add(new Node3(xx, yy, t.d + 1));
}
}
}
return -1;
}
}
class Node3{
int x,y,d;
public Node3(){
d = 0;
}
public Node3(int a,int b,int c){
x = a;
y = b;
d = c;
}
}
/**************************************************************
Problem: 2125
User: admin
Language: Java
Result: Accepted
Time:731 ms
Memory:41356 kb
****************************************************************/