Josif_tepe

Untitled

Aug 20th, 2025
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 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.     int di[] = {-1, 1, 0, 0};
  18.     int dj[] = {0, 0, -1, 1};
  19.     while(!q.empty()) {
  20.         int ci = q.front();
  21.         q.pop();
  22.         int cj = q.front();
  23.         q.pop();
  24.         int shortest_dist = q.front();
  25.         q.pop();
  26.        
  27.         if(ci == ei and cj == ej) {
  28.             cout << shortest_dist << endl;
  29.             return;
  30.         }
  31.      
  32.         for(int x = 0; x < 4; x++) {
  33.             int ti = ci + di[x];
  34.             int tj = cj + dj[x];
  35.            
  36.             if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and mat[ti][tj] != '#') {
  37.                 q.push(ti);
  38.                 q.push(tj);
  39.                 q.push(shortest_dist + 1);
  40.                 visited[ti][tj] = true;
  41.             }
  42.         }
  43.     }
  44. }
  45. int main() {
  46.     ios_base::sync_with_stdio(false);
  47.     cin >> n >> m;
  48.    
  49.     int si, sj, ei, ej;
  50.     for(int i = 0; i < n; i++) {
  51.         for(int j = 0; j < m; j++) {
  52.             cin >> mat[i][j];
  53.            
  54.             if(mat[i][j] == 'S') {
  55.                 si = i;
  56.                 sj = j;
  57.             }
  58.            
  59.             if(mat[i][j] == 'E') {
  60.                 ei = i;
  61.                 ej = j;
  62.             }
  63.         }
  64.     }
  65.     bfs(si, sj, ei, ej);
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment