var n,m,i,j,k,p,q,ii,nn:longint;x:string; f:array[0..101,0..101] of longint; ch:array[0..101,0..101] of char; procedure s(x:longint); var i,j:longint; begin if x>n*m then begin writeln('-1');exit;end; for i:=1 to n do for j:=1 to m do begin if f[i,j]=x then begin if ch[i-1,j]='-' then f[i-1,j]:=f[i,j]+1; if ch[i+1,j]='-' then f[i+1,j]:=f[i,j]+1; if ch[i,j-1]='-' then f[i,j-1]:=f[i,j]+1; if ch[i,j+1]='-' then f[i,j+1]:=f[i,j]+1; end; end; if f[p,q]<>0 then writeln(f[p,q]-1) else s(x+1); end; begin readln(nn); for ii:=1 to nn do begin readln(n,m); fillchar(f,sizeof(f),0); for i:=1 to n do begin readln(x); for j:=1 to m do begin ch[i,j]:=x[j]; if ch[i,j]='E' then begin ch[i,j]:='-'; p:=i; q:=j; end; if ch[i,j]='S' then f[i,j]:=1; end; end;s(1); end; end. /************************************************************** Problem: 2125 User: admin Language: Pascal Result: Wrong Answer ****************************************************************/