Josif_tepe

Untitled

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