#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

int main() {
  for(int tci = 0; ; tci++) {
    int W,H; scanf("%d%d", &W, &H); if(W==0) break;
    static char tbl[60][30];
    for(int y = 0; y < H; y++) {
      for(int x = 0; x < W; x++) {
        scanf(" %c", &tbl[y][x]);
      }
    }
    static int tim[60][30][2];
    for(int y = 0; y < H; y++) {
      for(int x = 0; x < W; x++) {
        tim[y][x][0] = tim[y][x][1] = -1;
      }
    }
    priority_queue<pair<pair<int,int>,pair<int,int> > > pq;
    for(int y = 0; y < H; y++) {
      for(int x = 0; x < W; x++) {
        if(tbl[y][x]=='S') {
          pq.push(make_pair(make_pair(0,0),make_pair(y,x)));
          pq.push(make_pair(make_pair(0,1),make_pair(y,x)));
        }
      }
    }
    int score = -1;
    while(!pq.empty()) {
      int t = pq.top().first.first;
      int d = pq.top().first.second;
      int y = pq.top().second.first;
      int x = pq.top().second.second;
      pq.pop();
      if(tim[y][x][d]!=-1) continue;
      tim[y][x][d]=-t;
      if(tbl[y][x]=='T') {
        score = -t;
        break;
      }
      for(int yy = max(0,y-3); yy <= min(H-1,y+3); yy++) {
        for(int xx = max(0,x-3); xx <= min(W-1,x+3); xx++) {
          bool ok = abs(yy-y)+abs(xx-x)<=3;
          if(d==0) ok = ok && x < xx;
          if(d==1) ok = ok && x > xx;
          ok = ok && tbl[yy][xx] != 'X';
          if(ok) {
            int cost = ('0' <= tbl[yy][xx] && tbl[yy][xx] <= '9') ? tbl[yy][xx]-'0' : 0;
            pq.push(make_pair(make_pair(t-cost,d^1),make_pair(yy,xx)));
          }
        }
      }
    }
    printf("%d\n", score);
  }
  return 0;
}