#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <queue>
#include <vector>
#include <tuple>
#include <cmath>
#define rep(i, n) for(i = 0; i < n; i++)
using namespace std;
typedef tuple<int, int, int> T;

int INF = 1e+9;
int w, h;
char s[60][31];
int dp[60][30][2];	//left:0, right:1

int solve() {
	int i, j, k;
	queue<T> que;
	
	rep(i, h) rep(j, w) rep(k, 2) dp[i][j][k] = INF;
	rep(i, h) {
		rep(j, w) {
			if (s[i][j] == 'S') {
				rep(k, 2) {
					dp[i][j][k] = 0;
					que.push(T(i, j, k));
				}
			}
		}
	}
	
	while (!que.empty()) {
		T now = que.front(); que.pop();
		int y = get<0>(now);
		int x = get<1>(now);
		int d = get<2>(now);
		int cst = dp[y][x][d];
		
		for (i = -2; i <= 2; i++) {
			for (j = 1; j <= 3; j++) {
				if (abs(i) + abs(j) > 3) continue;
				int ny = y + i;
				int nx = x;
				if (d == 0) nx += j;
				else nx -= j;
				if (ny < 0 || ny >= h || nx < 0 || nx >= w) continue;
				if (s[ny][nx] == 'X') continue;
				
				int ncst = 0;
				if ('0' <= s[ny][nx] && s[ny][nx] <= '9') {
					ncst = s[ny][nx] - '0';
				}
				ncst += cst;
				int nd = !d;
				
				if (dp[ny][nx][nd] > ncst) {
					dp[ny][nx][nd] = ncst;
					que.push(T(ny, nx, nd));
				}
			}
		}
	}
	
	int ans = INF;
	rep(i, h) {
		rep(j, w) {
			if (s[i][j] == 'T') {
				rep(k, 2) {
					ans = min(ans, dp[i][j][k]);
				}
			}
		}
	}
	if (ans >= INF) return -1;
	return ans;
}

int main() {
	while (cin >> w >> h) {
		if (!w) { break; }
		int i, j;
		rep(i, h) rep(j, w) cin >> s[i][j];
		int res = solve();
		cout << res << endl;
	}
	return 0;
}
