Josif_tepe

Untitled

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