Advertisement
ivangarvanliev

Untitled

Nov 11th, 2024
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int bfs(int si, int sj, int ei, int ej, int n, int m, vector<string>& grid) {
  5. vector<vector<bool>> visited(n, vector<bool>(m, false));
  6. queue<tuple<int, int, int>> q;
  7. q.push({si, sj, 0});
  8. visited[si][sj] = true;
  9.  
  10. int di[] = {-1, 1, 0, 0};
  11. int dj[] = {0, 0, -1, 1};
  12.  
  13. while (!q.empty()) {
  14. auto [ci, cj, dist] = q.front();
  15. q.pop();
  16.  
  17. if (ci == ei && cj == ej) return dist;
  18.  
  19. for (int k = 0; k < 4; k++) {
  20. int ni = ci + di[k];
  21. int nj = cj + dj[k];
  22.  
  23. if (ni >= 0 && ni < n && nj >= 0 && nj < m && !visited[ni][nj] && grid[ni][nj] != '#') {
  24. visited[ni][nj] = true;
  25. q.push({ni, nj, dist + 1});
  26. }
  27. }
  28. }
  29.  
  30. return -1;
  31. }
  32.  
  33. int main() {
  34. int n, m;
  35. cin >> n >> m;
  36. vector<string> grid(n);
  37. for (int i = 0; i < n; i++) {
  38. cin >> grid[i];
  39. }
  40.  
  41. int si = -1, sj = -1, ei = -1, ej = -1;
  42. for (int i = 0; i < n; i++) {
  43. for (int j = 0; j < m; j++) {
  44. if (grid[i][j] == 'S') {
  45. si = i;
  46. sj = j;
  47. } else if (grid[i][j] == 'E') {
  48. ei = i;
  49. ej = j;
  50. }
  51. }
  52. }
  53.  
  54. int directPath = bfs(si, sj, ei, ej, n, m, grid);
  55. if (directPath != -1) {
  56. cout << directPath << endl;
  57. return 0;
  58. }
  59.  
  60.  
  61. int longestPathWithOneBlockRemoval = -1;
  62. for (int i = 0; i < n; i++) {
  63. for (int j = 0; j < m; j++) {
  64. if (grid[i][j] == '#') {
  65.  
  66. grid[i][j] = '.';
  67. int pathWithRemoval = bfs(si, sj, ei, ej, n, m, grid);
  68. if (pathWithRemoval != -1) {
  69. longestPathWithOneBlockRemoval = max(longestPathWithOneBlockRemoval, pathWithRemoval);
  70. }
  71.  
  72. grid[i][j] = '#';
  73. }
  74. }
  75. }
  76.  
  77. cout << longestPathWithOneBlockRemoval << endl;
  78. return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement