#include "bits/stdc++.h"
using namespace std;
#define ff first
#define ss second
#define pp pop_back
#define ll long long
#define pb push_back
#define pq priority_queue
#define ls(v) (int)v.size()
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define wr cout << "------------------------" << endl
#define tt debug
const int INF = 1e9 + 7;
const int N = 1e3 + 5;
const int px[]={+1,-1,0,0,+1,+1,-1,-1};
const int py[]={0,0,+1,-1,+1,-1,-1,+1};
int n,m;
int dist[N][N][10];
char c[N][N];
pair<int,int>tele[20];
pair<int,int> go[N][N];
bool inside(int x,int y){
return (x >= 1 and y >= 1 and x <= n and y <= m);
}
signed main(){
#ifdef parad0x
freopen("file.in","r",stdin);
#endif
#define print(...) 42
ios::sync_with_stdio(false);cin.tie(nullptr);
cin >> n >> m;
for (int i = 1;i<=n;++i)
for (int j = 1;j<=m;++j){
cin >> c[i][j];
for(int z = 0;z<=9;++z)
dist[i][j][z] = INF;
}
int Sx,Sy,Ex,Ey;
for (int i = 1;i<=n;++i){
for (int j = 1;j<=m;++j){
if (c[i][j] == 'S')
Sx = i, Sy = j;
if (c[i][j] == 'E')
Ex = i, Ey = j;
if('1' <= c[i][j] and c[i][j] <= '9'){
int num = c[i][j] - '0';
if(tele[num].ff){
go[i][j] = tele[num];
go[tele[num].ff][tele[num].ss] = {i,j};
}
else
tele[num] = {i,j};
}
}
}
// for(int i = 1;i<=n;++i)
// for(int j = 1;j<=m;++j)
// cout << i << ' ' << j << ' ' << go[i][j].ff << ' ' << go[i][j].ss << endl;
pq<array<int,4>,vector<array<int,4>>,greater<array<int,4>>>q;
q.push({0,9,Sx,Sy});
dist[Sx][Sy][8] = 0;
while(!q.empty()){
auto [k,u,x,y] = q.top();
q.pop();
if(dist[x][y][u] < k)
continue;
if(x == Ex and y == Ey)
continue;
for(int z = 0;z<8;++z){
int xx = px[z] + x;
int yy = py[z] + y;
if(!inside(xx,yy) or c[xx][yy] == '#')
continue;
int kk = k + (z != u);
if(dist[xx][yy][z] > kk)
q.push({kk,z,xx,yy}), dist[xx][yy][z] = kk;
}
if(go[x][y].ff){
auto [xx,yy] = go[x][y];
if(dist[xx][yy][8] > k)
q.push({k,8,xx,yy}), dist[xx][yy][8] = k;
}
}
int ans = INF;
for(int z = 0;z<8;++z)
ans = min(ans,dist[Ex][Ey][z]);
cout << (ans == INF ? -1 : ans) << endl;
return 0;
}