View Code of Problem 2597

#include <bits/stdc++.h>
using namespace std;
int n, m;
char G[101][101];
int mini = 1e9;
int dir[][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int f[101][101] = {0};
void dfs(int x, int y, int cnt){
    f[x][y] = 1;
    for(int i = 0; i<4; i++){
        int nx = x + dir[i][0];
        int ny = y + dir[i][1];
        if(nx>=0&&nx<n&&ny>=0&&ny<m&&G[nx][ny]!='#'&&!f[nx][ny]){
            if(G[nx][ny]=='.'){
                dfs(nx, ny, cnt+1);
            }
            if(G[nx][ny]=='E'){
                mini = min(cnt+1, mini);
            }
        }
    }
    
    
}
int main(){
    
    while(scanf("%d %d", &n, &m)!=EOF){
        mini = 1e9;
        memset(f, 0, sizeof(f));
        for(int i = 0; i<n; i++){   
            for(int j = 0; j<m; j++){
                cin>>G[i][j];
            }
        }
        for(int i= 0; i<n; i++){
            for(int j = 0; j<m; j++){
                if(G[i][j]=='S'){
                    dfs(i, j, 0);
                }
            }
        }
        if(mini==1e9){
            cout<<0<<endl;
        }
        else{
            cout<<mini<<endl;
        }
        
    }
    return 0;
}

Double click to view unformatted code.


Back to problem 2597