CCCPaste

Untitled

#include 
#include 
using namespace std;


int main()
{
    int T;
    cin >> T;
    
    int di[] = {-1, 1, 0, 0};
    int dj[] = {0, 0, -1, 1};
    
    for(int t = 0; t < T; t++) {
        int n, m;
        cin >> n >> m;
        
        char mat[n][m];
        int si, sj;
        int 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);
        
        vector> dist(n, vector(m, -1));
        vector> visited(n, vector(m, false));
        
        while(!q.empty()) {
            int ci = q.front();
            q.pop();
            int cj = q.front();
            q.pop();
            int d = q.front();
            q.pop();
            
            dist[ci][cj] = d;
            
            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 mat[ti][tj] != 'T' and !visited[ti][tj]) {
                    q.push(ti);
                    q.push(tj);
                    q.push(d + 1);
                    visited[ti][tj] = true;
                }
            }
        }
        
        int najkratok_pat_od_S_do_E = dist[si][sj];
        int health = 100;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(isdigit(mat[i][j]) and dist[i][j] != -1) {
                    if(dist[i][j] < najkratok_pat_od_S_do_E) {
                        health -= (mat[i][j] - '0');
                    }
                }
            }
        }
        if(health < 0) {
            health = 0;
        }
        cout << health << endl;
        
    }
    return 0;

}