#include #include #include #include #include using namespace std; typedef long long ll; const int maxn = 1e5 + 10; const int INF = 2e9 + 10; const ll inf = 1e18 + 10; int n, m; char mat[1001][1001]; int di[] = {-1, 1, 0, 0}; int dj[] = {0, 0, -1, 1}; int dist[1001][1001]; int bfs(int si, int sj) { vector> visited(n, vector(m, false)); visited[si][sj] = true; queue q; q.push(si); q.push(sj); q.push(0); while(!q.empty()) { int ti = q.front(); q.pop(); int tj = q.front(); q.pop(); int distance = q.front(); q.pop(); dist[ti][tj] = distance; for(int it = 0; it < 4; ++it) { int ni = ti + di[it]; int nj = tj + dj[it]; if(ni < 0 or nj < 0 or ni >= n or nj >= m) continue; if(visited[ni][nj]) continue; if(mat[ni][nj] == 'T') continue; visited[ni][nj] = true; q.push(ni); q.push(nj); q.push(distance + 1); } } return 0; } int main() { ios_base::sync_with_stdio(false); // ifstream cin("in.txt"); int t; cin >> t; for(int T = 0; T < t; ++T) { cin >> n >> m; int si, sj; // starting position int ei, ej; // ending position 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; } } } for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { dist[i][j] = INF; } } bfs(ei, ej); int health = 100; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { if(mat[i][j] >= '0' and mat[i][j] <= '9') { if(dist[i][j] <= dist[si][sj]) { health -= (mat[i][j] - '0'); } } } } cout << max(health, 0) << endl; } return 0; }