Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<queue>
- using namespace std;
- int main()
- {
- int n,m;
- cin>>n>>m;
- char mat[n][m];
- int si,sj;
- 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;
- }
- }
- }
- queue<int>q;
- q.push(si);
- q.push(sj);
- q.push(0);
- bool visited[n][m];
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- {
- visited[i][j]=false;
- }
- }
- visited[si][sj]=true;
- int di[]={-1,1,0,0};
- int dj[]={0,0,-1,1};
- int distanca;
- while(!q.empty())
- {
- int ci=q.front();
- q.pop();
- int cj=q.front();
- q.pop();
- distanca=q.front();
- q.pop();
- if(mat[ci][cj]=='E')
- {
- cout<<distanca;
- return 0;
- }
- for(int i=0;i<4;i++)
- {
- int ti=ci+di[i];
- int tj=cj+dj[i];
- if(ti>=0 && ti<n && tj>=0 && tj<m && mat[ti][tj]!='#' && visited[ti][tj]==false )
- {
- visited[ti][tj]=true;
- q.push(ti);
- q.push(tj);
- q.push(distanca+1);
- }
- }
- }
- int maks=-2e9;
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- {
- for(int x=0;x<n;x++)
- {
- for(int y=0;y<m;y++)
- {
- visited[x][y]=false;
- }
- }
- if(mat[i][j]=='#')
- {
- mat[i][j]='.';
- q.push(si);
- q.push(sj);
- q.push(0);
- visited[si][sj]=true;
- while(!q.empty())
- {
- int ci=q.front();
- q.pop();
- int cj=q.front();
- q.pop();
- distanca=q.front();
- q.pop();
- if(mat[ci][cj]=='E')
- {
- if(maks<distanca)
- {
- maks=distanca;
- }
- while(!q.empty()) {
- q.pop();
- }
- break;
- }
- for(int k=0;k<4;k++)
- {
- int ti=ci+di[k];
- int tj=cj+dj[k];
- if(ti>=0 && ti<n && tj>=0 && tj<m && mat[ti][tj] != '#' && visited[ti][tj]==false)
- {
- visited[ti][tj]=true;
- q.push(ti);
- q.push(tj);
- q.push(distanca+1);
- }
- }
- }
- mat[i][j] = '#';
- }
- }
- }
- if(maks==-2e9)
- cout<<-1;
- else
- cout<<maks;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement