#include <bits/stdc++.h>
using namespace std;
struct haha {
  int x, y;
  haha() {}
  haha(int a, int b) : x(a), y(b) {}
};
int d[2][1000][1000], sum[1000001], r, c;
char m[1111][1111];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
void BFS(int idx, int x, int y) {
  queue<haha> q;
  q.push(haha(x, y));
  d[idx][x][y] = 0;
  while (!q.empty()) {
    haha u = q.front();
    if (idx == 1)
      if (isdigit(m[u.x][u.y])) sum[d[idx][u.x][u.y]] += m[u.x][u.y] - '0';
    q.pop();
    for (int i = 0; i < 4; i++) {
      int X = u.x + dx[i], Y = u.y + dy[i];
      if (X < 0 || X == r || Y < 0 || Y == c) continue;
      if (m[X][Y] == 'T') continue;
      if (d[idx][X][Y] == -1) {
        d[idx][X][Y] = d[idx][u.x][u.y] + 1;
        q.push(haha(X, Y));
      }
    }
  }
}
int main() {
  memset(d, -1, sizeof d);
  scanf("%d %d", &r, &c);
  for (int i = 0; i < r; i++) scanf("%s", m[i]);
  for (int i = 0; i < r; i++)
    for (int j = 0; j < c; j++)
      if (m[i][j] == 'E')
        BFS(1, i, j);
      else if (m[i][j] == 'S')
        BFS(0, i, j);
  for (int i = 1; i < 1000001; i++) sum[i] += sum[i - 1];
  int ans = 1000000000;
  for (int i = 0; i < r; i++)
    for (int j = 0; j < c; j++)
      if (m[i][j] != 'T' && (d[1][i][j] > 0))
        ans = min(ans, sum[d[0][i][j] + d[1][i][j]]);
  printf("%d\n", ans);
  return 0;
}
