#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void _updmin(T& x, const T& y) {
  if (x > y) x = y;
}
template <class T>
inline void _updmax(T& x, const T& y) {
  if (x < y) x = y;
}
const int maxn = 1001;
const int dx[5] = {0, 1, -1, 0, 0};
const int dy[5] = {0, 0, 0, 1, -1};
class pii {
 public:
  int x, y;
} d[maxn * maxn];
int n, m, sx, sy, ex, ey;
int a[maxn][maxn], dep[maxn][maxn];
int main() {
  ios::sync_with_stdio(0);
  int i, j, k;
  cin >> n >> m;
  for (i = 1; i <= n; i++) {
    string s;
    cin >> s;
    for (j = 1; j <= m; j++) {
      if (s[j - 1] == 'T')
        a[i][j] = -1;
      else if (s[j - 1] == 'S')
        a[i][j] = 0, sx = i, sy = j;
      else if (s[j - 1] == 'E')
        a[i][j] = 0, ex = i, ey = j;
      else
        a[i][j] = (int)s[j - 1] - 48;
    }
  }
  int head = 0, last = 0;
  d[last].x = ex, d[last].y = ey;
  dep[ex][ey] = 1;
  while (head <= last) {
    pii now = d[head];
    for (k = 1; k <= 4; k++) {
      int tx = now.x + dx[k], ty = now.y + dy[k];
      if (tx > 0 && tx <= n && ty > 0 && ty <= m)
        if (dep[tx][ty] == 0 && a[tx][ty] != -1) {
          dep[tx][ty] = dep[now.x][now.y] + 1;
          last++;
          d[last].x = tx, d[last].y = ty;
        }
    }
    head++;
  }
  if (dep[sx][sy] == 0) {
    cout << -1 << endl;
    return 0;
  }
  int ans = 0;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (dep[i][j] != 0 && dep[i][j] <= dep[sx][sy] && a[i][j] != -1)
        ans += a[i][j];
  cout << ans << endl;
  return 0;
}
