// Aizu 1150: Cliff Climbing
// 2017.9.17 bal4u@uu

#include <stdio.h>
#include <ctype.h>
#include <string.h>

typedef struct { int r, c, t, lr; } Q;
Q q[50005]; int top, end;
char map[62][32]; int h, w;
int mk[62][32][2];
int mv[2][9][2] = {
	{{-2, 1},{-1, 2},{-1, 1},{0, 3},{0, 2},{0, 1},{1, 2},{1, 1},{2, 1}},
	{{-2,-1},{-1,-2},{-1,-1},{0,-3},{0,-2},{0,-1},{1,-2},{1,-1},{2,-1}} };

int main()
{
	int i, r, c, r2, c2, t, t2, lr, ans;
	char s[10];

	while (scanf("%d%d", &w, &h) && w) {
		memset(mk, -1, sizeof(mk));
		for (r = 0; r < h; r++) for (c = 0; c < w; c++) scanf("%s", s), map[r][c] = *s;
		for (ans = -1, top = end = 0, r = h-1, c = 0; c < w; c++) if (map[r][c] == 'S') {
			q[end].r = r, q[end].c = c, q[end].t = 0, q[end++].lr = 0, mk[r][c][0] = 0;
			q[end].r = r, q[end].c = c, q[end].t = 0, q[end++].lr = 1; mk[r][c][1] = 0;
		}
		while (top < end) {
			r = q[top].r, c = q[top].c, t = q[top].t, lr = !(q[top++].lr);
			if (map[r][c] == 'T') { if (ans < 0 || t < ans) ans = t; continue; }
			for (i = 0; i < 9; i++) {
				r2 = r + mv[lr][i][0], c2 = c + mv[lr][i][1];
				if (r2 < 0 || r2 >= h || c2 < 0 || c2 >= w || map[r2][c2] == 'X') continue;
				if (mk[r2][c2][lr] >= 0 && t >= mk[r2][c2][lr]) continue;
				mk[r2][c2][lr] = t;
				t2 = t; if (isdigit(map[r2][c2])) t2 += map[r2][c2] - '0';
				q[end].r = r2, q[end].c = c2, q[end].t = t2, q[end++].lr = lr;
			}
		}
		printf("%d\n", ans);
    }
	return 0;
}