Josif_tepe

Untitled

Feb 18th, 2026
285
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 <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.     while(!q.empty()) {
  40.         int ci = q.front();
  41.         q.pop();
  42.         int cj = q.front();
  43.         q.pop();
  44.         int dist = q.front();
  45.         q.pop();
  46.        
  47.         if(ci == ei and cj == ej) {
  48.             cout << dist << endl;
  49.             break;
  50.         }
  51.        
  52.         if(ci + 1 < n and mat[ci + 1][cj] != '#' and !visited[ci + 1][cj]) {
  53.             q.push(ci + 1);
  54.             q.push(cj);
  55.             q.push(dist + 1);
  56.             visited[ci + 1][cj] = true;
  57.         }
  58.         if(ci - 1 >= 0 and mat[ci - 1][cj] != '#' and !visited[ci - 1][cj]) {
  59.             q.push(ci - 1);
  60.             q.push(cj);
  61.             q.push(dist + 1);
  62.             visited[ci - 1][cj] = true;
  63.         }
  64.         if(cj + 1 < m and mat[ci][cj + 1] != '#' and !visited[ci][cj + 1]) {
  65.             q.push(ci);
  66.             q.push(cj + 1);
  67.             q.push(dist + 1);
  68.             visited[ci][cj + 1] = true;
  69.         }
  70.         if(cj - 1 >= 0 and mat[ci][cj - 1] != '#' and !visited[ci][cj - 1]) {
  71.             q.push(ci);
  72.             q.push(cj - 1);
  73.             q.push(dist + 1);
  74.             visited[ci][cj - 1] = true;
  75.         }
  76.        
  77.     }
  78.    
  79.    
  80.    
  81.    
  82.     return 0;
  83. }
  84.  
  85. /*
  86. 5 7
  87. ####..#
  88. S...#.#
  89. .......
  90. #.#.#.E
  91. #######
  92.  
  93.  **/
  94.  
Advertisement
Add Comment
Please, Sign In to add comment