Advertisement
Derga

Untitled

Aug 24th, 2023 (edited)
829
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <climits>
  2. #include <cstdint>
  3. #include <iomanip>
  4. #include <iostream>
  5. #include <queue>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. struct Point
  11. {
  12.     int x;
  13.     int y;
  14. };
  15.  
  16. bool operator==(const Point& lhs, const Point& rhs)
  17. {
  18.     return tie(lhs.x, lhs.y) == tie(rhs.x, rhs.y);
  19. }
  20.  
  21. Point GetNewPoint(const vector< vector< int > >& field, int x, int y, int dx, int dy)
  22. {
  23.     while (field[x + dx][y + dy] == 0)
  24.     {
  25.         x += dx;
  26.         y += dy;
  27.     }
  28.     if (field[x + dx][y + dy] == 2)
  29.     {
  30.         x += dx;
  31.         y += dy;
  32.     }
  33.     return { x, y };
  34. }
  35.  
  36. int32_t GetMinMovesCount(const vector< vector< int > >& field)
  37. {
  38.     vector< vector< bool > > is_visited(field.size(), vector< bool >(field.front().size(), false));
  39.  
  40.     int x_starting_pos = 1;
  41.     int y_starting_pos = 1;
  42.     is_visited[x_starting_pos][y_starting_pos] = true;
  43.  
  44.     queue< pair< Point, int > > q;
  45.     q.push({ { x_starting_pos, y_starting_pos }, 0 });
  46.     while (!q.empty())
  47.     {
  48.         Point cur_point = q.front().first;
  49.  
  50.         int x = cur_point.x;
  51.         int y = cur_point.y;
  52.        
  53.         int moves_count = q.front().second;
  54.         q.pop();
  55.  
  56.         if (field[x][y] == 2)
  57.         {
  58.             return moves_count;
  59.         }
  60.  
  61.         for (int dx = -1; dx <= 1; ++dx)
  62.         {
  63.             for (int dy = -1; dy <= 1; ++dy)
  64.             {
  65.                 if (dx * dx + dy * dy != 1)
  66.                     continue;
  67.  
  68.                 Point new_point = GetNewPoint(field, x, y, dx, dy);
  69.                 if (is_visited[new_point.x][new_point.y])
  70.                     continue;
  71.  
  72.                 q.push({ new_point, moves_count + 1 });
  73.                 is_visited[new_point.x][new_point.y] = true;
  74.             }
  75.         }
  76.     }
  77. }
  78.  
  79. int main()
  80. {
  81.     int32_t rows_count, columns_count;
  82.     cin >> rows_count >> columns_count;
  83.  
  84.     vector< vector< int32_t > > field(rows_count + 2, vector< int >(columns_count + 2, INT32_MAX));
  85.     for (int32_t i = 1; i < field.size() - 1; ++i)
  86.     {
  87.         for (int32_t j = 1; j < field.front().size() - 1; ++j)
  88.         {
  89.             cin >> field[i][j];
  90.         }
  91.     }
  92.  
  93.     cout << GetMinMovesCount(field);
  94.  
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement