#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<mem.h>
#include<queue>
using namespace std;
#define ll long long
const int inf = 0x3f3f3f3f;
char g[1010][1010];
bool vis[1010][1010];
int a[4] = {0,0,1,-1};
int b[4] = {1,-1,0,0};
struct node{
int x,y,step;
};
queue<node>q;
int n,x,y,ex,ey,ans;
void dfs(int x,int y)
{
node now,next;
now.x = x,now.y = y,now.step = 0;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
for(int i = 0; i <4; i++)
{
next.x = now.x + a[i];
next.y = now.y + b[i];
next.step = now.step + 1;
if(next.x <= n && next.x > 0 && next.y > 0 && next.y <= n && !vis[next.x][next.y] && g[next.x][next.y] != '#')
{
vis[next.x][next.y] = true;
q.push(next);
}
if(g[next.x][next.y] == 'E')
{
ans = min(ans,next.step);
}
}
}
}
int main()
{
while(~scanf("%d",&n))
{
ans = inf;
memset(vis,false,sizeof(vis));
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
scanf(" %c",&g[i][j]);
if(g[i][j] == 'S')
{
x = i,y = j;
}
}
}
dfs(x,y);
if(ans != inf)
printf("%d\n",ans);
else
printf("-1\n");
}
}