#include<bits/stdc++.h>
using namespace std;
long long n,m;
char a[1005][1005];
vector<pair<long long,long long>> g[10];
long long dx[] = {0,0,1,1,1,-1,-1,-1};
long long dy[] = {1,-1,-1,0,1,-1,0,1};
long long distS[1005][1005][10],distT[1005][1005][10];
bool checkDoi(long long x,long long y) {
if (y == 0) y = 1;
else if (y == 1) y = 0;
else if (y == 2) y = 7;
else if (y == 3) y = 6;
else if (y == 4) y = 5;
else if (y== 5) y = 4;
else if (y == 6) y = 3;
else y = 2;
return (x == y);
}
void bfs(long long dist[1005][1005][10],pair<long long,long long> S) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int x = 0; x < 8; x++) dist[i][j][x] = 1e18;
}
}
queue<pair<pair<long long,long long>,long long>> q;
dist[S.first][S.second][8] = 0;
q.push({S,8});
while(!q.empty()) {
long long u = q.front().first.first,v = q.front().first.second,dir = q.front().second;
q.pop();
for(int i = 0; i < 8; i++) {
long long nu = u +dx[i],nv= v+dy[i];
if (nu > 0 && nu <= n && nv > 0 && nv <= m && a[nu][nv] != '#' && dist[nu][nv][i] > dist[u][v][dir]+(dir!= i)) {
dist[nu][nv][i] = dist[u][v][dir]+(dir!= i);
q.push({{nu,nv},i});
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
pair<long long,long long> S,E;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
if (a[i][j] == 'S') S = {i,j};
if (a[i][j] == 'E') E = {i,j};
if (a[i][j] >= '0' && a[i][j] <= '9') {
g[a[i][j]-'0'].push_back({i,j});
}
}
}
bfs(distS,S);
bfs(distT,E);
long long ans = 1e18;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int x =0 ; x < 8;x++) {
for (int y = 0; y < 8; y++) {
ans = min(ans,distS[i][j][x]+distT[i][j][y]);
if (a[i][j] >= '0' && a[i][j] <= '9') {
if (g[a[i][j]-'0'][0].first == i && g[a[i][j]-'0'][0].second == j) {
ans = min(ans,distS[i][j][x]+distT[g[a[i][j]-'0'][1].first][g[a[i][j]-'0'][1].second][y]+checkDoi(x,y));
} else {
ans = min(ans,distS[i][j][x]+distT[g[a[i][j]-'0'][0].first][g[a[i][j]-'0'][0].second][y]+checkDoi(x,y));
}
}
}
}
}
}
cout << ans;
}