Untitled
#include <iostream> #include <vector> #include <queue> using namespace std; const int maxn = 1005; const int INF = 2e9; int n, m; char mat[maxn][maxn]; bool visited[maxn][maxn]; const int di[] = {-1, 1, 0, 0}; const int dj[] = {0, 0, -1, 1}; int bfs_basic(int si, int sj, int ei, int ej) { queue<int> q; q.push(si); q.push(sj); q.push(0); for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { visited[i][j] = false; } } visited[si][sj] = true; 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) { return cekor; } 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] and mat[ti][tj] != '#') { q.push(ti); q.push(tj); q.push(cekor + 1); visited[ti][tj] = true; } } } return -1; } int s_dist[maxn][maxn]; void bfs_S(int si, int sj) { queue<int> q; q.push(si); q.push(sj); q.push(0); for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { visited[i][j] = false; } } visited[si][sj] = 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] == '#') { s_dist[ti][tj] = cekor + 1; } else { q.push(ti); q.push(tj); q.push(cekor + 1); } visited[ti][tj] = true; } } } } int e_dist[maxn][maxn]; void bfs_e(int si, int sj) { queue<int> q; q.push(si); q.push(sj); q.push(0); for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { visited[i][j] = false; } } visited[si][sj] = 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] == '#') { e_dist[ti][tj] = cekor + 1; } else { q.push(ti); q.push(tj); q.push(cekor + 1); } visited[ti][tj] = true; } } } } int main() { ios_base::sync_with_stdio(false); cin >> n >> m; int si = 0, sj = 0, ei = 0, ej = 0; 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; } s_dist[i][j] = -1; e_dist[i][j] = -1; } } int tmp = bfs_basic(si, sj, ei, ej); if(tmp != -1) { cout << tmp << endl; return 0; } bfs_S(si, sj); bfs_e(ei, ej); int res = -1; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(mat[i][j] == '#' and s_dist[i][j] != -1 and e_dist[i][j] != -1) { res = max(res, s_dist[i][j] + e_dist[i][j]); } } } cout << res << endl; return 0; } /* S..#E ###.. #.... ..... **/
Leave a Comment