Advertisement
Josif_tepe

Untitled

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