Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- using namespace std;
- const int maxn = 1005;
- char mat[maxn][maxn];
- int n, m;
- int main() {
- cin >> 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<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- vector<vector<int>> dist_S(n, vector<int>(m, -1));
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1, 1};
- visited[si][sj] = true;
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int d = q.front();
- q.pop();
- if(ci == ei and cj == ej) {
- cout << d << endl;
- return 0;
- }
- if(mat[ci][cj] == '#') {
- dist_S[ci][cj] = d;
- continue;
- }
- 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 !visited[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(d + 1);
- visited[ti][tj] = true;
- }
- }
- }
- q.push(ei);
- q.push(ej);
- q.push(0);
- vector<vector<int>> dist_E(n, vector<int>(m, -1));
- for(int i =0 ; i < n; i++) {
- for(int j = 0; j < m; j++) {
- visited[i][j] = false;
- }
- }
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int d = q.front();
- q.pop();
- if(mat[ci][cj] == '#') {
- dist_E[ci][cj] = d;
- continue;
- }
- 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 !visited[ti][tj]) {
- q.push(ti);
- q.push(tj);
- q.push(d + 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] == '#' and 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