egogoboy

Лабиринт с тигром

Jul 22nd, 2022
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. int inf = 2000000;
  8. vector<int> dx = { 1, 0, -1, 0 };
  9. vector<int> dy = { 0, 1, 0, -1 };
  10. queue<pair<int, int>> q;
  11.  
  12. void bfs(vector<vector<int>>& map) {
  13.     while (!q.empty()) {
  14.  
  15.         pair<int, int> v, u;
  16.         v = q.front();
  17.         u = v;
  18.         q.pop();
  19.  
  20.         for (int i = 0; i < 4; ++i) {
  21.  
  22.             u.first += dx[i];
  23.             u.second += dy[i];
  24.             if (u.first > 0 && u.first < map.size() - 1 && u.second > 0 && u.second < map[0].size() - 1 && map[u.first][u.second] != -1) {
  25.                
  26.                 if (map[u.first][u.second] > map[v.first][v.second] + 1) {
  27.                     map[u.first][u.second] = min(map[u.first][u.second], map[v.first][v.second] + 1);
  28.                     q.push(u);
  29.                 }
  30.  
  31.             }
  32.             u.first -= dx[i];
  33.             u.second -= dy[i];
  34.  
  35.         }
  36.  
  37.     }
  38. }
  39.  
  40. int main() {
  41.  
  42.     std::ifstream fin("input.txt");
  43.     std::ofstream fout("output.txt");
  44.  
  45.     int n, m;
  46.     fin >> n >> m;
  47.  
  48.     vector<vector<int>> map(n, vector<int>(m, 0)), pmap(n, vector<int>(m, 0));
  49.     pair<int, int> tiger;
  50.     for (int i = 0; i < n; ++i) {
  51.         for (int j = 0; j < m; ++j) {
  52.             char c;
  53.             fin >> c;
  54.             if (c == '#') {
  55.                 map[i][j] = -1;
  56.                 pmap[i][j] = -1;
  57.             }
  58.             else {
  59.                 map[i][j] = inf;
  60.                 pmap[i][j] = inf;
  61.             }
  62.             if (c == 'T') {
  63.                 tiger.first = i; tiger.second = j;
  64.                 map[i][j] = 0;
  65.                 pmap[i][j] = inf;
  66.             }
  67.         }
  68.     }
  69.  
  70.     q.push(tiger);
  71.     bfs(map);
  72.  
  73.     tiger.first = 1; tiger.second = 1, pmap[1][1] = 0;
  74.     q.push(tiger);
  75.     bfs(pmap);
  76.  
  77.     fout << pmap[n - 2][m - 2] << endl;
  78.    
  79.     if (pmap[n - 2][m - 2] >= map[n - 2][m - 2]) {
  80.         fout << "No" << endl;
  81.     }
  82.     else {
  83.         fout << "Yes" << endl;
  84.     }
  85.  
  86.     return 0;
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment