#include
#include
using namespace std;
int main()
{
int T;
cin >> T;
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};
while(T--) {
int n, m;
cin >> n >> m;
char mat[n][m];
int si, sj, ei, ej;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> mat[i][j];
if(mat[i][j] == 'S') {
si = i;
sj = j;
}
if(mat[i][j] == 'E') {
ei = i;
ej = j;
}
}
}
queue q;
q.push(ei);
q.push(ej);
q.push(0);
bool visited[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
visited[i][j] = false;
}
}
int distanca_od_S = -1;
visited[ei][ej] = true;
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int cekor = q.front();
q.pop();
if(ci == si and cj == sj) {
distanca_od_S = cekor;
while(!q.empty()) {
q.pop();
}
break;
}
for(int k = 0; k < 4; k++) {
int ti = ci + di[k];
int tj = cj + dj[k];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and mat[ti][tj] != 'T') {
q.push(ti);
q.push(tj);
q.push(cekor + 1);
visited[ti][tj] = true;
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
visited[i][j] = false;
}
}
visited[ei][ej] = true;
q.push(ei);
q.push(ej);
q.push(0);
int health_units = 100;
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int cekor = q.front();
q.pop();
if(isdigit(mat[ci][cj])) {
if(cekor <= distanca_od_S) {
health_units -= (mat[ci][cj] - '0');
}
}
for(int k = 0; k < 4; k++) {
int ti = ci + di[k];
int tj = cj + dj[k];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and mat[ti][tj] != 'T') {
q.push(ti);
q.push(tj);
q.push(cekor + 1);
visited[ti][tj] = true;
}
}
}
if(health_units < 0) {
health_units = 0;
}
cout << health_units << endl;
}
return 0;
}