#include <iostream>
#include <queue>
#include <vector>
#include <cmath>
#define INF 100000000
#define REP(i, a, n) for(int i = (a); i < (n); i++)
using namespace std;

struct state { int y, x, f, d; };
class Compare {
public:
  bool operator()(struct state a, struct state b) {
    return a.d > b.d;
  }
};

int H, W;
char S[60][30];
int dp[60][30][3];

int isin(int y, int x) {
  return 0 <= y && y < H && 0 <= x && x < W;
}

int main(void) {
  while(cin >> W >> H, H && W) {
    priority_queue<struct state, vector<struct state>, Compare> q;

    REP(i, 0, H) REP(j, 0, W) REP(k, 0, 3) dp[i][j][k] = INF;

    REP(i, 0, H) {
      REP(j, 0, W) {
        cin >> S[i][j];
        if(S[i][j] == 'S') {
          struct state l = { i, j, -1, 0 };
          struct state r = { i, j, 1, 0 };
          q.push(l);
          q.push(r);
        }
      }
    }

    long ans = -1;
    while(!q.empty()) {
      struct state c = q.top();
      q.pop();

      // cout << c.y << ", " << c.x << ", " << c.f << ", " << c.d << endl;

      if(dp[c.y][c.x][c.f + 1] <= c.d) continue;
      dp[c.y][c.x][c.f + 1] = c.d;
      if(S[c.y][c.x] == 'T') {
        ans = dp[c.y][c.x][c.f + 1];
        break;
      }

      REP(i, -2, 3) REP(j, 1, 4) {
        int ny = c.y + i, nx = c.x - j * c.f;
        if(abs(c.y - ny) + abs(c.x - nx) > 3) continue;
        if(S[ny][nx] == 'X') continue;
        if(!isin(ny, nx)) continue;
        int nd = c.d + ('0' <= S[ny][nx] && S[ny][nx] <= '9' ? S[ny][nx] - '0' : 0);
        int nf = -c.f;
        if(dp[ny][nx][nf + 1] <= nd) continue;
        struct state n = { ny, nx, nf, nd };
        q.push(n);
        // cout << "  " << n.y << ", " << n.x << ", " << n.f << ", " << n.d << endl;
      }
    }

    cout << ans << endl;
  }

  return 0;
}