Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- 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));
- 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, dist] = q.front();
- q.pop();
- if (ci == ei && cj == ej) return dist;
- 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] && grid[ni][nj] != '#') {
- visited[ni][nj] = true;
- q.push({ni, nj, dist + 1});
- }
- }
- }
- return -1;
- }
- 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;
- }
- }
- }
- int directPath = bfs(si, sj, ei, ej, n, m, grid);
- if (directPath != -1) {
- cout << directPath << endl;
- return 0;
- }
- int longestPathWithOneBlockRemoval = -1;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (grid[i][j] == '#') {
- grid[i][j] = '.';
- int pathWithRemoval = bfs(si, sj, ei, ej, n, m, grid);
- if (pathWithRemoval != -1) {
- longestPathWithOneBlockRemoval = max(longestPathWithOneBlockRemoval, pathWithRemoval);
- }
- grid[i][j] = '#';
- }
- }
- }
- cout << longestPathWithOneBlockRemoval << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment