#include <bits/stdc++.h>
using namespace std;

const int INF = 1<<28;
const int MAXH = 60;
const int MAXW = 30;
const int dx[13] = {0,0,0,0,0,   1,1,1,  -1,-1,-1, 2, -2};
const int dy[13] = {2,1,0,-1,-2, 1,0,-1, 1,0,-1,   0, 0};

int w, h;
char s[MAXH][MAXW];

struct State {
  int lx, ly, rx, ry, f, cost;

  bool operator < (const State &s) const {
    if(lx != s.lx) return lx < s.lx;
    if(ly != s.ly) return ly < s.ly;
    if(rx != s.rx) return rx < s.rx;
    if(ry != s.ry) return ry < s.ry;
    if(f != s.f) return f < s.f;
    return false;
  }

  bool ok() const {
    return lx < rx && abs(lx-rx) + abs(ly-ry) <= 3 &&
      0 <= min(lx,rx) && max(lx,rx) < w &&
      0 <= min(ly,ry) && max(ly,ry) < h;
  }
};

struct GT {
  bool operator () (const State &a, const State &b) const {
    return a.cost > b.cost;
  }
};

int main() {
  while(cin >> w >> h && (w|h)) {
    for(int i = 0; i < h; ++i) {
      for(int j = 0; j < w; ++j) {
        cin >> s[i][j];
      }
    }
    try {
      map<State, int> cost;
      priority_queue<State, vector<State>, GT> que;
      for(int x = 0; x < w; ++x) {
        for(int y = 0; y < h; ++y) {
          if(s[y][x] != 'S') continue;
          State src = {x, y, x, y, 0, 0};
          src.f = 0;
          cost[src] = 0;
          que.push(src);
          src.f = 1;
          cost[src] = 0;
          que.push(src);
        }
      }
      while(que.size()) {
        const State a = que.top();
        que.pop();
        if(cost.count(a) && a.cost > cost[a]) continue;
        for(int k = 0; k < 13; ++k) {
          State b; int x, y;
          if(a.f) {
            b = (State){a.rx+dx[k]-1, a.ry+dy[k], a.rx, a.ry, !a.f, a.cost};
            x = b.lx, y = b.ly;
          } else {
            b = (State){a.lx, a.ly, a.lx+dx[k]+1, a.ly+dy[k], !a.f, a.cost};
            x = b.rx, y = b.ry;
          }
          if(!b.ok()) continue;
          if(s[y][x] == 'X') continue;
          if(s[y][x] == 'T') throw a.cost;
          if(s[y][x] != 'S') b.cost += s[y][x] - '0';
          if(cost.count(b) && b.cost >= cost[b]) continue;
          cost[b] = b.cost;
          que.push(b);
        }
      }
      throw -1;
    } catch(int res) {
      cout << res << endl;
    }
  }
  return 0;
}