#include #include #include #include #include #include using namespace std; int main() { int n, m; cin >> n >> m; vector> mat(n, vector(m)); bool visited[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]; visited[i][j] = false; if(mat[i][j] == 'S') { si = i; sj = j; } if(mat[i][j] == 'E') { ei = i; ej = j; } } } queue q; q.push(si); q.push(sj); q.push(0); int di[] = {-1, 1, 0, 0}; int dj[] = {0, 0, -1, 1}; while(!q.empty()) { int ci = q.front(); q.pop(); int cj = q.front(); q.pop(); int cekor = q.front(); q.pop(); if(ci == ei and cj == ej) { cout << cekor << endl; return 0; } for(int i = 0; i < 4; i++) { int ti = ci + di[i]; int tj = cj + dj[i]; if(ti >= 0 and ti < n and tj >= 0 and tj < m and mat[ti][tj] != '#' and !visited[ti][tj]) { q.push(ti); q.push(tj); q.push(cekor + 1); visited[ti][tj] = true; } } } return 0; } /** ....S##... E....##.. ##..## ...###... **/