#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>

using namespace std;
typedef long long LL;
static const double EPS = 1e-9;

#define FOR(i,k,n) for (int i=(k); i<(int)(n); ++i)
#define REP(i,n) FOR(i,0,n)
struct state{
  int leg;
  int x,y;
  int cost;
  state(int x,int y,int cost,int leg) : x(x), y(y), cost(cost), leg(leg) {}
};
bool operator < (state s,state r){
  return s.cost > r.cost;
}
int main(void){
  int w,h;
  while(cin>>w>>h,w){
    char grid[100][100];
    int mincost[100][100][2];
    memset(mincost,-1,sizeof(mincost));
    REP(y,h)REP(x,w){
      cin>>grid[y][x];
    }
    priority_queue<state> que;
    REP(y,h)REP(x,w){
      if(grid[y][x]=='S'){
        que.push(state(x,y,0,0));
        que.push(state(x,y,0,1));
      }
    }
    bool output=false;
    while(!que.empty()){
      state s = que.top(); que.pop();
      if(grid[s.y][s.x]=='T'){
        cout<<s.cost<<endl;
        output=true;
        break;
      }
      if(mincost[s.y][s.x][s.leg]!=-1&&s.cost>=mincost[s.y][s.x][s.leg]) continue;
      mincost[s.y][s.x][s.leg] = s.cost;
      if(s.leg==0){
        for(int dx = 1; dx<=3; dx++){
          for(int dy = -3; dy<=3; dy++){
            if(dx + abs(dy) <= 3){
              int nx = s.x + dx;
              int ny = s.y + dy;
              if(0<=nx&&nx<w&&0<=ny&&ny<h&&grid[ny][nx]!='X'){
                char ch = grid[ny][nx];
                que.push(state(nx,ny,s.cost+((ch>='0'&&ch<='9')?ch-'0':0),1));
              }
            }
          }
        }
      }
      if(s.leg==1){
        for(int dx = -1; dx>=-3; dx--){
          for(int dy = -3; dy<=3; dy++){
            if(abs(dx) + abs(dy) <= 3){
              int nx = s.x + dx;
              int ny = s.y + dy;
              if(0<=nx&&nx<w&&0<=ny&&ny<h&&grid[ny][nx]!='X'){
                char ch = grid[ny][nx];
                que.push(state(nx,ny,s.cost+((ch>='0'&&ch<='9')?ch-'0':0),0));
              }
            }
          }
        }
      }
    }
    if(!output) cout<<-1<<endl;
  }
  return 0;
}