#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<string>
#include<map>
#define INF 1000000000
#define all(c) c.begin(),c.end()
#define uni(c) c.erase(unique(all(c)),c.end())
#define pb push_back
using namespace std;
typedef pair<int,int> P;
typedef pair<bool,P> iP;
typedef pair<int,iP> iPi;
int w,h;
int dx[]={1,1,1,1,1,2,2,2,3,-1,-1,-1,-1,-1,-2,-2,-2,-3},dy[]={-2,-1,0,1,2,-1,0,1,0,-2,-1,0,1,2,-1,0,1,0};
int d[62][32][2];
map<P,bool> mp;
//(i,(b,((i,i),(i,i))))
bool inf(P a){
	if(a.second>=0&&a.second<w&&a.first>=0&&a.first<h)
		return true;
	return false;
}

int dij(vector<vector<int> > f,vector<P> v){
	priority_queue<iPi,vector<iPi> , greater<iPi> > que;
	for(int i=0;i<h;i++)
	for(int j=0;j<w;j++)
	for(int z=0;z<2;z++)
		d[i][j][z]=INF;
	for(int i=0;i<v.size();i++){
		que.push(iPi(0,iP(false,v[i])));
		que.push(iPi(0,iP(true,v[i])));
		d[v[i].first][v[i].second][0]=0;
		d[v[i].first][v[i].second][1]=0;
	}
	
	while(!que.empty()){
		iPi p=que.top();
		P pos=p.second.second;
		bool which=p.second.first;
		int nc=p.first;
		que.pop();
		if(d[pos.first][pos.second][which]<nc){
			continue;
		}
		if(mp[pos]){
			return nc;
		}
		d[pos.first][pos.second][which]=nc;
		if(which)
		for(int i=0;i<9;i++){
			int ny=pos.first+dy[i],nx=pos.second+dx[i];
			if(inf(P(ny,nx))&&d[ny][nx][which^1]>nc+f[ny][nx]){
				que.push(iPi(nc+f[ny][nx],iP(which^1,P(ny,nx))));
			}
		}
		else
		for(int i=9;i<18;i++){
			int ny=pos.first+dy[i],nx=pos.second+dx[i];
			if(inf(P(ny,nx))&&d[ny][nx][which^1]>nc+f[ny][nx]){
				que.push(iPi(nc+f[ny][nx],iP(which^1,P(ny,nx))));
			}
		}
	}
	return -1;
}
int main(){
	while(cin>>w>>h,w||h){
		vector<vector<int> > f(h,vector<int>(w));
		vector<P> v(2);
		mp.clear();
		v.clear();
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				char c;
				cin>>c;//f[i][j];
				if(c=='S'){
					v.pb(P(i,j));
					f[i][j]=0;
				}else if(c=='T'){
					mp[P(i,j)]=true;
					f[i][j]=0;
				}else if(c=='X'){
					f[i][j]=INF;
				}else{
					f[i][j]=c-'0';
				}
			}
		}
		sort(all(v));
		cout<<dij(f,v)<<endl;
	}
	return 0;
}