#include<stdio.h>
#include<math.h>

int main(void)
{
  int w,h;
  char s[60][30];
  int i,j,m,n,c;
  int dp[60][30][2];
  int tmp1,tmp2,min;

  while(1){
    scanf("%d %d ",&w,&h);
    if(w==0 && h==0)break;
    for(i=0;i<h;i++){
      for(j=0;j<w;j++){
	scanf("%c ",&s[i][j]);
      }
    }

    for(i=0;i<h;i++){
      for(j=0;j<w;j++){
	dp[i][j][0] = -1;
	dp[i][j][1] = -1;
      }
    }

    for(i=0;i<w;i++){
      if(s[h-1][i] == 'S'){
        dp[h-1][i][0] = 0;
        dp[h-1][i][1] = 0;
      }
    }

    
    while(1){
      c=0;
      for(i=0;i<h;i++){
	for(j=0;j<w;j++){ 
	  if(dp[i][j][0] >= 0){
	    for(m=-2;m<=2;m++){
	      for(n=1;n<=3;n++){
		if(i+m>=0 && i+m<h && j+n<w && fabs(m)+n<=3 && s[i+m][j+n]!='X'){
		  tmp1 = dp[i+m][j+n][1];
		  if(s[i+m][j+n] == 'S' || s[i+m][j+n] == 'T'){
		    tmp2 = dp[i][j][0];
		  }else{
		    tmp2 = dp[i][j][0] + s[i+m][j+n] - '0';
		  }
		  if(tmp1 < 0 || tmp1 > tmp2){
		    dp[i+m][j+n][1] = tmp2;
		    c++;
		  }
		}
	      }
	    }
	  }
	  if(dp[i][j][1] >= 0){
	    for(m=-2;m<=2;m++){
	      for(n=1;n<=3;n++){
		if(i+m>=0 && i+m<h && j-n>=0 && fabs(m)+n<=3 && s[i+m][j-n]!='X'){
		  tmp1 = dp[i+m][j-n][0];
		  if(s[i+m][j-n] == 'S' || s[i+m][j-n] == 'T'){
		    tmp2 = dp[i][j][1];
		  }else{
		    tmp2 = dp[i][j][1] + (int)(s[i+m][j-n] - '0');
		  }
		  if(tmp1 < 0 || tmp1 > tmp2){
		    dp[i+m][j-n][0] = tmp2;
		    c++;
	          }
		}
	      }
	    }
	  }
	}
      }
      if(c==0)break;
    }

    min = -1;
    for(i=0;i<w;i++){
      if(s[0][i] == 'T'){
	 for(j=0;j<2;j++){
           if(min < 0 || (dp[0][i][j] > 0 && min > dp[0][i][j]))min = dp[0][i][j];
	}
      }
    }

    printf("%d\n",min);
    
  }
  return 0;
}