#include <bits/stdc++.h>
#define pii pair<int, int>
#define fi first
#define se second
using namespace std;
const int N = 1e6 + 5, M = 1005;
const int INF = 1e9 + 7;
int n, m, dis[M][M];
int cnt[4], id[M][M][4];
char a[M][M];
pii pos[11], ST, EN;
pii nxt[M][M];
bool mark[4][N];
vector<pii> v[4][N];
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
for (int i = 0; i < 10; ++i)
pos[i] = {-1, -1};
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
cin >> a[i][j];
if (a[i][j] == 'S')
ST = {i, j}; else
if (a[i][j] == 'E')
EN = {i, j}; else
if ('0' <= a[i][j] && a[i][j] <= '9'){
pii &x = pos[a[i][j] - '0'];
if (x != make_pair(-1, -1))
nxt[i][j] = x,
nxt[x.fi][x.se] = {i, j};
else
x = {i, j};
}
dis[i][j] = INF;
}
//0: doc, 1: ngang, 2: cheo chinh, 3: cheo phu
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j){
if (a[i][j] == '#') continue;
if (i == 1 || a[i - 1][j] == '#'){
++cnt[0];
for (int t = i; t <= n; ++t){
if (a[t][j] == '#') break;
v[0][id[t][j][0] = cnt[0]].push_back({t, j});
}
}
if (j == 1 || a[i][j - 1] == '#'){
++cnt[1];
for (int t = j; t <= m; ++t){
if (a[i][t] == '#') break;
v[1][id[i][t][1] = cnt[1]].push_back({i, t});
}
}
if (i == 1 || j == 1 || a[i - 1][j - 1] == '#'){
++cnt[2];
for(int x = i, y = j; x <= n && y <= m; ++x, ++y){
if (a[x][y] == '#') break;
v[2][id[x][y][2] = cnt[2]].push_back({x, y});
}
}
if (i == 1 || j == m || a[i - 1][j + 1] == '#'){
++cnt[3];
for(int x = i, y = j; x <= n && y; ++x, --y){
if (a[x][y] == '#') break;
v[3][id[x][y][3] = cnt[3]].push_back({x, y});
}
}
}
deque<pii> q;
dis[ST.fi][ST.se] = 0;
q.push_front({ST.fi, ST.se});
while (!q.empty()){
pii x = q.front(); q.pop_front();
for (int i = 0; i < 4; ++i)
if (!mark[i][id[x.fi][x.se][i]]){
mark[i][id[x.fi][x.se][i]] = 1;
for (pii t: v[i][id[x.fi][x.se][i]])
if (dis[t.fi][t.se] > dis[x.fi][x.se] + 1)
dis[t.fi][t.se] = dis[x.fi][x.se] + 1,
q.push_back({t.fi, t.se});
}
if ('0' <= a[x.fi][x.se] && a[x.fi][x.se] <= '9'){
pii u = nxt[x.fi][x.se];
if (dis[u.fi][u.se] > dis[x.fi][x.se])
dis[u.fi][u.se] = dis[x.fi][x.se],
q.push_front({u.fi, u.se});
}
}
// for (int i = 1; i <= n; ++i){
// for (int j = 1; j <= m; ++j) cout << dis[i][j] << " "; cout << "\n";
// }
cout << (dis[EN.fi][EN.se] == INF ? -1 : dis[EN.fi][EN.se]);
}