#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pi pair<int, int>
#define pii pair<int, pi>
#define fi first
#define se second
#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#endif
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int n, m;
char g[1005][1005];
int dist[1005][1005][10];
int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};
vector <pi> v[10];
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i++)for(int j = 1; j <= m; j++)for(int k = 0; k < 10; k++)dist[i][j][k] = 1e9;
queue <pii> q;
int e1, e2;
for (int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++){
cin >> g[i][j];
if(g[i][j] == 'S'){
dist[i][j][8] = 0;
q.push({i, {j, 8}});
}
else if(g[i][j] >= '1' && g[i][j] <= '9'){
int x = g[i][j] - '0';
v[x].push_back({i, j});
}
else if(g[i][j] == 'E')e1 = i, e2 = j;
}
}
while (!q.empty()){
int x = q.front().fi, y = q.front().se.fi, z = q.front().se.se;
q.pop();
if(g[x][y] >= '1' && g[x][y] <= '9'){
int tmp = g[x][y] - '0';
if(v[tmp].size() == 2){
pi dst = (v[tmp][0] == make_pair(x, y) ? v[tmp][1] : v[tmp][0]);
if(dist[dst.fi][dst.se][8] > dist[x][y][z]){
dist[dst.fi][dst.se][8] = dist[x][y][z];
q.push({dst.fi, {dst.se, 8}});
}
}
}
for(int i = 0; i < 8; i++){
int x1 = x + dx[i], y1 = y + dy[i];
if(x1 < 1 || x1 > n || y1 < 1 || y1 > m)continue;
if(g[x1][y1] == '#')continue;
int nd = dist[x][y][z] + (i != z);
if(dist[x1][y1][i] > nd){
dist[x1][y1][i] = nd;
q.push({x1, {y1, i}});
}
}
}
int ans = 1e9;
for(int i = 0; i < 9; i++)ans = min(ans, dist[e1][e2][i]);
cout << (ans == 1e9 ? -1 : ans);
}
main(){
ios::sync_with_stdio(0);cin.tie(0);
int tc = 1;
//cin >> tc;
for(int tc1=1;tc1<=tc;tc1++){
// cout << "Case #" << tc1 << ": ";
solve();
}
}