#include<bits/stdc++.h>
using namespace std;
int n,m,c;
char q[1000][1000];
bool f=false;
int ans=INT_MAX;
void dfs(int a,int b,int k){
	

	
	int fx[5]={0,1,0,-1};
	int fy[5]={1,0,-1,0};
	for(int i=0;i<=3;i++){
		int tx=a+fx[i];
		int ty=b+fy[i];
	
		if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&q[tx][ty]=='.'){
			//if(tx==x1x&&ty==y1y) f=true;
			q[tx][ty]='#';
            dfs(tx,ty,k+1);
            q[tx][ty]='.';
		}
}
} 
int main(){
cin>>n>>m;

for(int i=1;i<=n;i++){
	for(int j=1;j<=m;j++){
	cin>>q[i][j];
	//c[i][j]=INT_MAX;
	}
}

for(int i=1;i<=n;i++){
	for(int j=1;j<=m;j++){
	if(q[i][j]=='S'){
		x=i;
		y=j;
	} 
	if(q[i][j]=='E'){
		x1x=i;
		y1y=j;
		
	} 
}
}
   
 q[x][y]='#';
    dfs(x,y,0);
//	for(int i=1;i<=n;i++){
//	for(int j=1;j<=m;j++){
//	if(c[i][j]<INT_MAX)cout<<c[i][j]<<" ";
//	}
//	cout<<endl;
//}
if(ans==INT_MAX){
	cout<<-1;
}
else cout<<ans*c;

//cout<<x<<" "<<y<<" "<<x1x<<" "<<y1y<<" "<<c[x1x][y1y-1];


	return 0;
}

/**************************************************************
	Problem: 2109
	User: chenyubo
	Language: C
	Result: Compile Error
****************************************************************/