Josif_tepe

Untitled

Aug 20th, 2025
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6. const int maxn = 1005;
  7. int n, m;
  8. char mat[maxn][maxn];
  9.  
  10. void bfs(int si, int sj, int ei, int ej) {
  11.     queue<int> q;
  12.     q.push(si);
  13.     q.push(sj);
  14.     q.push(0);
  15.    
  16.     vector<vector<bool>> visited(n, vector<bool>(m, false));
  17.    
  18.     while(!q.empty()) {
  19.         int ci = q.front();
  20.         q.pop();
  21.         int cj = q.front();
  22.         q.pop();
  23.         int shortest_dist = q.front();
  24.         q.pop();
  25.        
  26.         if(ci == ei and cj == ej) {
  27.             cout << shortest_dist << endl;
  28.             return;
  29.         }
  30.        
  31.         if(ci + 1 < n and mat[ci + 1][cj] != '#' and !visited[ci + 1][cj]) {
  32.             q.push(ci + 1);
  33.             q.push(cj);
  34.             q.push(shortest_dist + 1);
  35.             visited[ci + 1][cj] = true;
  36.         }
  37.        
  38.         if(ci - 1 >= 0 and mat[ci - 1][cj] != '#' and !visited[ci - 1][cj]) {
  39.             q.push(ci - 1);
  40.             q.push(cj);
  41.             q.push(shortest_dist + 1);
  42.             visited[ci - 1][cj] = true;
  43.         }
  44.         if(cj + 1 < m and mat[ci][cj + 1] != '#' and !visited[ci][cj + 1]) {
  45.             q.push(ci);
  46.             q.push(cj + 1);
  47.             q.push(shortest_dist + 1);
  48.             visited[ci][cj + 1] = true;
  49.         }
  50.         if(cj - 1 >= 0 and mat[ci][cj - 1] != '#' and !visited[ci][cj - 1]) {
  51.             q.push(ci);
  52.             q.push(cj - 1);
  53.             q.push(shortest_dist + 1);
  54.             visited[ci][cj - 1] = true;
  55.         }
  56.     }
  57. }
  58. int main() {
  59.     ios_base::sync_with_stdio(false);
  60.     cin >> n >> m;
  61.    
  62.     int si, sj, ei, ej;
  63.     for(int i = 0; i < n; i++) {
  64.         for(int j = 0; j < m; j++) {
  65.             cin >> mat[i][j];
  66.            
  67.             if(mat[i][j] == 'S') {
  68.                 si = i;
  69.                 sj = j;
  70.             }
  71.            
  72.             if(mat[i][j] == 'E') {
  73.                 ei = i;
  74.                 ej = j;
  75.             }
  76.         }
  77.     }
  78.     bfs(si, sj, ei, ej);
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment