#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> mp;
ll inf = 1e10;
typedef pair<mp,mp> mmp; //cost left-right-state(0,1)

int main(){
    while(1){
	int w,h;
	cin>>w>>h;
	if(w==0)break;
	vector<vector<ll> > s(h+8,vector<ll>(w+8,inf) );
	vector<vector<vector<bool> > > used(h+8,vector<vector<bool> >(w+8,vector<bool>(2,false) ) );
	vector<vector<bool> > goal(h+8,vector<bool>(w+8,false) );
	priority_queue<mmp,vector<mmp>,greater<mmp> > q;
	for(int i=4;i<h+4;i++){
	    for(int j=4;j<w+4;j++){
		char tmp;
		cin>>tmp;
		if(tmp=='S'){
		    s[i][j] = 0;
		    q.push(mmp( mp(0,0),mp(i,j) ) );
		    q.push(mmp( mp(0,1),mp(i,j) ) );
		}else if(tmp=='T'){
		    s[i][j] = 0;
		    goal[i][j] = true;
		}else if(tmp=='X'){
		    used[i][j][0] = true;
		    used[i][j][1] = true;
		}else{
		    s[i][j] = tmp-'0';
		}
	    }
	}
	bool flag = true;
	while(!q.empty() ){
	    mmp now = q.top();
	    q.pop();
	    ll cost = now.first.first;
	    ll state = now.first.second;
	    ll x = now.second.first;
	    ll y = now.second.second;
	    if(goal[x][y]){
		cout<<cost<<endl;
		flag  = false;
		break;
	    }
	    if(s[x][y] == inf) continue;
	    if(used[x][y][state])continue;
	    used[x][y][state] = true;
	    ll ddx = 1;
	    if(state == 1)ddx *= -1;
	    state = (state+1)%2;
	    for(int i=1;i<=3;i++){
		for(int j=-3+i ; j <= 3-i  ;j++){
		    ll nx = x + j;
		    ll ny = y + i*ddx;
		    ll nc = cost + s[nx][ny];
		    if(used[nx][ny][state])continue;
		    q.push( mmp( mp( nc , state ), mp( nx,ny ) )  );
		}
	    }
	}
	if(flag) cout<<-1<<endl;
    }
    return 0;
}

