Advertisement
Josif_tepe

Untitled

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