#include "stdafx.h"
#include <iostream>
#include <limits>
using namespace std;
int n,row,col;
int leftDir,rightDir;
int leftStep,rightStep,minStep;
int totalStep = 1;
int sPositionX,sPositionY,ePositionX,ePositionY;
char data[50][50];
int leftBonus[4][2] = {{1,0},{0,-1},{-1,0},{0,1}};
int rightBonus[4][2] = {{0,1},{-1,0},{0,-1},{1,0}};
int plus[8] = {1,0,0,1,0,-1,-1,0};
int dfs(int x, int y, int dir, char method){
int bonus[4][2];
int newX,newY,newDir;
int dis = 0;
for(int i=0; i<4; i++){
dis = (i+dir)%4;
newDir = (dis + 3)%4;
if(method == 'l'){
newX = x + leftBonus[dis][0];
newY = y + leftBonus[dis][1];
}else{
newX = x + rightBonus[dis][0];
newY = y + rightBonus[dis][1];
}
if(data[newX][newY] == '#' || data[newX][newY] == 'S') continue;
else if(data[newX][newY] == 'E'){
totalStep++;
return totalStep;
}else{
totalStep++;
return dfs(newX, newY, newDir, method);
}
}
}
int dp(int i, int j){
if(i>=1 && i<=row && j>=1 && j<=col){
int num = 0;
if(data[i][j] == 'S'){
data[i][j] = '#';
return 1 + std::min(std::min(dp(i+1,j),dp(i,j+1)),std::min(dp(i-1,j),dp(i,j-1)));
}
if(data[i][j] == '#'){
return 9999;
}
if(data[i][j] == 'E'){
return 1;
}
for(int k=0; k<8; k+=2){
if(data[i+plus[k]][j+plus[k+1]] == '#'){
num++;
}
}
if(num == 3){
data[i][j] = '#';
return 1 + std::min(std::min(dp(i+1,j),dp(i,j+1)),std::min(dp(i-1,j),dp(i,j-1)));
}
if(data[i][j] == '.'){
data[i][j] = '#';
return 1 + std::min(std::min(dp(i+1,j),dp(i,j+1)),std::min(dp(i-1,j),dp(i,j-1)));
}
}else{
return 99999;
}
}
int getDirection(int x, int y, char method){
if(method == 'l'){
if(x == row) return 1;
if(y == 1) return 2;
if(x == 1) return 3;
if(y == col) return 0;
}else{
if(x == row) return 0;
if(y == 1) return 3;
if(x == 1) return 2;
if(y == col) return 1;
}
}
int main(){
cin >> (int)n;
for(int i=0; i<n; i++){
cin >> col;
cin >> row;
memset(data,'#',sizeof(data));
for(int j=1; j<=row; j++){
for(int k=1; k<=col; k++){
cin >> data[j][k];
if(data[j][k] == 'S'){
sPositionX = j;
sPositionY = k;
}else if(data[j][k] == 'E'){
ePositionX = j;
ePositionY = k;
}
}
}
leftDir = getDirection(sPositionX, sPositionY,'l');
rightDir = getDirection(sPositionX, sPositionY,'r');
leftStep = dfs(sPositionX,sPositionY,leftDir,'l');
cout << "leftStep:" << leftStep << endl;
totalStep = 1;
rightStep = dfs(sPositionX,sPositionY,rightDir,'r');
cout << "rightStep:" << rightStep << endl;
totalStep = 1;
minStep = dp(sPositionX, sPositionY);
cout << "minStep:" << minStep << endl;
}
return 0;
}