Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- vector<vector<int>> bfs(int si, int sj, int ei, int ej, int n, int m, vector<string>& grid) {
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- vector<vector<int>> dist(n, vector<int>(m, -1));
- queue<tuple<int, int, int>> q;
- q.push({si, sj, 0});
- visited[si][sj] = true;
- int di[] = {-1, 1, 0, 0};
- int dj[] = {0, 0, -1, 1};
- while (!q.empty()) {
- auto [ci, cj, d] = q.front();
- q.pop();
- if (ci == ei && cj == ej) {
- cout << d << endl;
- exit(0);
- }
- if(grid[ci][cj] == '#') {
- dist[ci][cj] = d;
- continue;
- }
- for (int k = 0; k < 4; k++) {
- int ni = ci + di[k];
- int nj = cj + dj[k];
- if (ni >= 0 && ni < n && nj >= 0 && nj < m && !visited[ni][nj]) {
- visited[ni][nj] = true;
- q.push({ni, nj, d + 1});
- }
- }
- }
- return dist;
- }
- int main() {
- int n, m;
- cin >> n >> m;
- vector<string> grid(n);
- for (int i = 0; i < n; i++) {
- cin >> grid[i];
- }
- int si = -1, sj = -1, ei = -1, ej = -1;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (grid[i][j] == 'S') {
- si = i;
- sj = j;
- } else if (grid[i][j] == 'E') {
- ei = i;
- ej = j;
- }
- }
- }
- vector<vector<int>> dist_S = bfs(si, sj, ei, ej, n, m, grid);
- int longest_path = -1;
- vector<vector<int>> dist_E = bfs(ei, ej, si, sj, n, m, grid);
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(grid[i][j] == '#' and dist_S[i][j] != -1 and dist_E[i][j] != -1) {
- longest_path = max(longest_path, dist_S[i][j] + dist_E[i][j]);
- }
- }
- }
- cout << longest_path << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement