#include <bits/stdc++.h>   using namespace std;   struct state {     int x, y, d;     state(){};     state(int _x, int _y, int _d) { x = _x, y = _y, d = _d; };   };   int main() {     int r, c;     int dx[4] = {1, 0, -1, 0};     int dy[4] = {0, 1, 0, -1};     while (cin >> r >> c) {       char temp;       int map[1010][1010];       vector<state> opp;       pair<int, int> start, end;       for (int i = 0; i < r; i++)         for (int j = 0; j < c; j++) {           cin >> temp;           if (temp >  0  && temp <=  9 ) opp.push_back(state(i, j, temp -  0 ));           if (temp ==  S ) start = pair<int, int>(i, j);           if (temp ==  E ) end = pair<int, int>(i, j);           if (temp ==  T )             map[i][j] = -1;           else             map[i][j] = 1222333444;         }       map[end.first][end.second] = 0;       queue<pair<int, int> > next;       next.push(end);       while (!next.empty()) {         pair<int, int> now = next.front();         next.pop();         for (int j = 0; j < 4; j++) {           int tempx = now.first + dx[j];           int tempy = now.second + dy[j];           if (tempx < 0 || tempx > r - 1 || tempy < 0 || tempy > c - 1) continue;           if (map[tempx][tempy] == -1) continue;           if (map[tempx][tempy] == 1222333444) {             map[tempx][tempy] = map[now.first][now.second] + 1;             next.push(pair<int, int>(tempx, tempy));           }         }       }       int sum = 0;       for (int i = 0; i < opp.size(); i++) {         int tempx = opp[i].x;         int tempy = opp[i].y;         if (map[tempx][tempy] <= map[start.first][start.second]) sum += opp[i].d;       }       cout << sum << endl;     }     return 0;   }   