#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define maxn 1005
#define mi LLONG_MIN
#define ma LLONG_MAX
#define mod 1000000007
#define pb push_back
#define S second
#define F first
int a[maxn][maxn];
int dist[maxn][maxn];
bool used[11];
vector<vector<pair<int, int>>> pairs(11);
int n, m;
void bfs(pair<int, int> s)
{
priority_queue<pair<int, pair<int, int>>> q;
q.push({0, s});
dist[s.F][s.S] = 0;
while (!q.empty())
{
int c = -q.top().F, x = q.top().S.F, y = q.top().S.S;
q.pop();
if (dist[x][y] < c)
continue;
if (a[x][y] > 0 && !used[a[x][y]])
{
pair<int, int> fx = pairs[a[x][y]][0];
pair<int, int> sx = pairs[a[x][y]][1];
if (fx == make_pair(x, y))
{
q.push({-c, sx});
}
else
{
q.push({-c, fx});
}
used[a[x][y]] = 1;
}
for (int i = 1; x - i >= 0; i++)
{
if (a[x - i][y] == -1)
{
break;
}
if (dist[x - i][y] > c + 1)
{
dist[x - i][y] = c + 1;
q.push({-c - 1, {x - i, y}});
}
}
for (int i = 1; y - i >= 0; i++)
{
if (a[x][y - i] == -1)
{
break;
}
if (dist[x][y - i] > c + 1)
{
dist[x][y - i] = c + 1;
q.push({-c - 1, {x, y - i}});
}
}
for (int i = 1; x + i < n; i++)
{
if (a[x + i][y] == -1)
{
break;
}
if (dist[x + i][y] > c + 1)
{
dist[x + i][y] = c + 1;
q.push({-c - 1, {x + i, y}});
}
}
for (int i = 1; y + i < m; i++)
{
if (a[x][y + i] == -1)
{
break;
}
if (dist[x][y + i] > c + 1)
{
dist[x][y + i] = c + 1;
q.push({-c - 1, {x, y + i}});
}
}
for (int i = 1; y + i < m && x + i < n; i++)
{
if (a[x + i][y + i] == -1)
{
break;
}
if (dist[x + i][y + i] > c + 1)
{
dist[x + i][y + i] = c + 1;
q.push({-c - 1, {x + i, y + i}});
}
}
for (int i = 1; y + i < m && x - i >= 0; i++)
{
if (a[x - i][y + i] == -1)
{
break;
}
if (dist[x - i][y + i] > c + 1)
{
dist[x - i][y + i] = c + 1;
q.push({-c - 1, {x - i, y + i}});
}
}
for (int i = 1; y - i >= 0 && x + i < n; i++)
{
if (a[x + i][y - i] == -1)
{
break;
}
if (dist[x + i][y - i] > c + 1)
{
dist[x + i][y - i] = c + 1;
q.push({-c - 1, {x + i, y - i}});
}
}
for (int i = 1; y - i >= 0 && x - i >= 0; i++)
{
if (a[x - i][y - i] == -1)
{
break;
}
if (dist[x - i][y - i] > c + 1)
{
dist[x - i][y - i] = c + 1;
q.push({-c - 1, {x - i, y - i}});
}
}
}
}
int32_t main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
for (int i = 0; i < maxn; i++)
{
for (int j = 0; j < maxn; j++)
{
dist[i][j] = ma;
}
}
cin >> n >> m;
pair<int, int> s, e;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
char x;
cin >> x;
if (x == 'S')
{
s = {i, j};
a[i][j] = 0;
}
else if (x == 'E')
{
e = {i, j};
a[i][j] = 0;
}
else if (x == '.')
{
a[i][j] = 0;
}
else if (x == '#')
{
a[i][j] = -1;
}
else
{
a[i][j] = x - '0';
pairs[a[i][j]].pb({i, j});
}
}
}
bfs(s);
if (dist[e.F][e.S] != ma)
{
cout << dist[e.F][e.S];
}
else
{
cout << -1;
}
}