#include<iostream>
#include<vector>
#include<queue>
#include<cstdlib>
#include<cmath>
#include<cstdio>

using namespace std;

typedef pair<int,int> P;

struct State{
  int x,y,t;
  bool isR;
  State(){}
  State(int a, int b, int c, bool d):
    x(a),y(b),t(c),isR(d){}
  bool operator < (const State& s) const {return t > s.t;}
};

const int MW = 31;
const int MH = 61;
const int INF = (1<<25);

int M[MH][MW],T[MH][MW][2],w,h;
vector<P> S;
vector<P> G;

void print(){
  for(int i = 0; i < h; i++){
    for(int x = 0; x < 2; x++){
      for(int j = 0; j < w; j++) 
	if(T[i][j][x] == INF) cout << "  X";
	else printf("%3d",T[i][j][x]);
      cout << "                 ";
    } 
    cout << endl;
  }
  cout << endl << endl;
}

bool isInside(int x, int y) {return 0<=x&&x<w&&0<=y&&y<h;}

void init(){
  for(int i = 0; i < MH; i++)
    for(int j = 0; j < MW; j++) T[i][j][0] = T[i][j][1] = INF;
}

void input(){
  for(int i = 0; i < h; i++)
    for(int j = 0; j < w; j++){
      char c;
      cin >> c;
      if(c == 'X') M[i][j] = INF;
      else if(c == 'T'){
	M[i][j] = 0;
	G.push_back(P(j,i));
      }else if(c == 'S'){
	M[i][j] = 0;
	S.push_back(P(j,i));
      }else M[i][j] = c-'0';
    }
}

int solve(bool R){
  
  init();

  priority_queue<State> Q;

  for(int i = 0; i < S.size(); i++){
    int sx = S[i].first;
    int sy = S[i].second;
    Q.push(State(sx,sy,0,R));
    T[sy][sx][R] = 0;
  }

  while(!Q.empty()){
    State now = Q.top();
    Q.pop();
    if(T[now.y][now.x][now.isR] < now.t) continue;
    
    for(int i = 1; i <= 3; i++)
      for(int j = -2; j <= 2; j++){
	int mx = i,my = j;
	if(now.isR) mx *= -1;
	int nx = now.x+mx;
	int ny = now.y+my;
	
	//	if(abs(mx) + abs(my) <= 3) cout << now.isR << " " <<  mx << " " << my << " " << endl;
	if(isInside(nx,ny) && abs(mx)+abs(my) <= 3 && T[ny][nx][!now.isR] > now.t+M[ny][nx]){
	  T[ny][nx][!now.isR] = now.t+M[ny][nx];
	  Q.push(State(nx,ny,now.t+M[ny][nx],!now.isR));
	}
      }
  }

  //print();
  int ans = INF;

  for(int i = 0; i < G.size(); i++) ans = min(ans,min(T[G[i].second][G[i].first][0],T[G[i].second][G[i].first][1]));

  return ans;
}

int main(){

  while(cin >> w >> h && w+h){
    S.clear();
    G.clear();
    input();
    int ans = min(solve(true),solve(false));
    if(ans == INF) cout << "-1" << endl;
    else cout << ans << endl;
  }
  return 0;
}