#include<bits/stdc++.h>
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3f
#define EPS (1e-10)
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef long long ll;
typedef pair<int, int>P;

char s[60][30], buf[2];
int d[60][30][60][30][2];
struct st {
	int lx, ly, rx, ry, c;
	bool b;
};
bool operator<(st a, st b) {
	return a.c > b.c;
}
int C(char c) {
	if (isdigit(c))return c - '0';
	return 0;
}
int w, h;
inline void update(st p, priority_queue<st>&que) {
	for (int k = -2; k <= 2; k++) {
		for (int t = 1; t <= 3 - abs(k); t++) {
			if (p.b) {
				int nx = p.lx + k, ny = p.ly + t;
				if (0 <= nx&&nx < h && 0 <= ny&&ny < w&&s[nx][ny] != 'X') {
					int&u = d[p.lx][p.ly][nx][ny][!p.b];
					int c = p.c + C(s[nx][ny]);
					if (u > c) {
						u = c; que.push({ p.lx,p.ly,nx,ny,u,!p.b });
					}
				}
			}
			else {
				int nx = p.rx + k, ny = p.ry - t;
				if (0 <= nx&&nx < h && 0 <= ny&&ny < w&&s[nx][ny] != 'X') {
					int&u = d[nx][ny][p.rx][p.ry][!p.b];
					int c = p.c + C(s[nx][ny]);
					if (u > c) {
						u = c; que.push({ nx,ny,p.rx,p.ry,u,!p.b });
					}
				}
			}
		}
	}
}
int main() {
	while (scanf("%d%d", &w, &h), w) {
		memset(d, 0x3f, sizeof(d));
		priority_queue<st>que;
		rep(i, h)rep(j, w) {
			scanf("%s", buf); s[i][j] = buf[0];
		}
		rep(j, w) {
			int i = h - 1;
			if (s[i][j] == 'S') {
				update({ i,j,0,0,0,1 }, que); update({ 0,0,i,j,0,0 }, que);
			}
		}
		while (!que.empty()) {
			st p = que.top(); que.pop();
			if (d[p.lx][p.ly][p.rx][p.ry][p.b] != p.c)continue;
			update(p, que);
		}
		int Min = INF;
		rep(i, h)rep(j, w)rep(k, h)rep(t, w)rep(y, 2) {
			if (s[i][j] == 'T' || s[k][t] == 'T')Min = min(Min, d[i][j][k][t][y]);
		}
		if (Min == INF)puts("-1");
		else printf("%d\n", Min);
	}
}