#include
#include
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
char mat[n][m];
int si, sj; // za S
int ei, ej; // za E
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> mat[i][j];
if(mat[i][j] == 'S') {
si = i;
sj = j;
}
if(mat[i][j] == 'E') {
ei = i;
ej = j;
}
}
}
bool visited[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
visited[i][j] = false;
}
}
// bfs da vidime dali ima direkten pat od S do E
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};
queue q;
q.push(si);
q.push(sj);
q.push(0);
visited[si][sj] = true;
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int dist = q.front();
q.pop();
if(mat[ci][cj] == 'E') {
cout << dist << endl;
return 0; // ja zavrsuvame programata bidejki mozeme od S do E da stigneme bez problemi
}
for(int k = 0; k < 4; k++) {
int ti = ci + di[k];
int tj = cj + dj[k];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited[ti][tj]) {
visited[ti][tj] = true;
q.push(ti);
q.push(tj);
q.push(dist + 1);
}
}
}
int dist_from_S_to_each_wall[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
dist_from_S_to_each_wall[i][j] = -1;
visited[i][j] = false;
}
}
q.push(si);
q.push(sj);
q.push(0);
visited[si][sj] = true;
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int dist = q.front();
q.pop();
if(mat[ci][cj] == '#') {
dist_from_S_to_each_wall[ci][cj] = dist;
continue;
}
for(int k = 0; k < 4; k++) {
int ti = ci + di[k];
int tj = cj + dj[k];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj]) {
visited[ti][tj] = true;
q.push(ti);
q.push(tj);
q.push(dist + 1);
}
}
}
int dist_from_E_to_each_wall[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
dist_from_E_to_each_wall[i][j] = -1;
visited[i][j] = false;
}
}
q.push(ei);
q.push(ej);
q.push(0);
visited[ei][ej] = true;
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int dist = q.front();
q.pop();
if(mat[ci][cj] == '#') {
dist_from_E_to_each_wall[ci][cj] = dist;
continue;
}
for(int k = 0; k < 4; k++) {
int ti = ci + di[k];
int tj = cj + dj[k];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj]) {
visited[ti][tj] = true;
q.push(ti);
q.push(tj);
q.push(dist + 1);
}
}
}
int rezultat = -1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mat[i][j] == '#') {
if(dist_from_S_to_each_wall[i][j] != -1 and dist_from_E_to_each_wall[i][j] != -1) {
rezultat = max(rezultat, dist_from_S_to_each_wall[i][j] + dist_from_E_to_each_wall[i][j]);
}
}
}
}
cout << rezultat << endl;
return 0;
}
/*
4 5
S..#E
###..
#....
.....
*/