#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)   FOR(i,0,n)
#define pb emplace_back
typedef long long ll;
typedef pair<int,int> pint;

typedef pair<pint,pint> ppi;
pint ss[2001];
const int dx[]={1,1,1,1,1,2,2,2,3},dy[]={2,1,0,-1,-2,1,0,-1,0};
char s[61][31];
int d[2001][2];
int INF=1000100010;
int n,cur,w,h;
int dijkstra(){
    priority_queue<ppi,vector<ppi>,greater<ppi> > pq;
    rep(i,n)rep(j,2) d[i][j]=INF;
    rep(i,cur){
        d[ss[i].first+ss[i].second*w][0]=d[ss[i].first+ss[i].second*w][1]=0;
        pq.push({{0,0},{ss[i].first,ss[i].second}});
        pq.push({{0,1},{ss[i].first,ss[i].second}});
    }
    while(!pq.empty()){
        ppi pi=pq.top();pq.pop();
        int cost=pi.first.first,lr=pi.first.second;
        int x=pi.second.first,y=pi.second.second;
        if(d[x+y*w][lr]<pi.first.first) continue;
        rep(i,9){
            int p=1;
            if(lr==0) p=-1;
            int tx=x+dx[i]*p,ty=y+dy[i];
            if(tx>=0&&tx<w&&ty>=0&&ty<h&&s[ty][tx]!='X'){
                if(s[ty][tx]=='T') return cost;
                else if(isdigit(s[ty][tx])){
                    int tt=s[ty][tx]-'0';
                    if(d[tx+ty*w][1-lr]>cost+tt){
                        d[tx+ty*w][1-lr]=cost+tt;
                        pq.push({{cost+tt,1-lr},{tx,ty}});
                    }
                }
            }
        }
    }
    return -1;
}
int main(){
    while(cin>>w>>h,w|h){
        n=w*h;
        cur=0;
        rep(i,h)rep(j,w){
            cin>>s[i][j];
            if(s[i][j]=='S') ss[cur++]={j,i};
        }
        cout<<dijkstra()<<endl;
    }
    return 0;
}

