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];
- bool visited[n][m];
- int dist_S[n][m];
- int dist_E[n][m];
- int si, sj, 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;
- }
- dist_S[i][j] = -1;
- dist_E[i][j] = -1;
- }
- }
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- visited[si][sj] = true;
- 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(mat[ci][cj] == 'E') {
- 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 !visited[ti][tj]) {
- if(mat[ti][tj] == '#') {
- dist_S[ti][tj] = cekor + 1;
- }
- else {
- q.push(ti);
- q.push(tj);
- q.push(cekor + 1);
- }
- visited[ti][tj] = true;
- }
- }
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- visited[i][j] = false;
- }
- }
- q.push(ei);
- q.push(ej);
- q.push(0);
- visited[ei][ej] = true;
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int cekor = q.front();
- q.pop();
- 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 !visited[ti][tj]) {
- if(mat[ti][tj] == '#') {
- dist_E[ti][tj] = cekor + 1;
- }
- else {
- q.push(ti);
- q.push(tj);
- q.push(cekor + 1);
- }
- visited[ti][tj] = true;
- }
- }
- }
- int res = -1;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(mat[i][j] == '#') {
- if(dist_S[i][j] != -1 and dist_E[i][j] != -1) {
- res = max(res, dist_S[i][j] + dist_E[i][j]);
- }
- }
- }
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement