Advertisement
Mirbek

Один конь

Dec 23rd, 2021
1,080
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 22;
  6.  
  7. int n;
  8. int f1, s1;
  9. int f2, s2;
  10. int used[N][N];
  11. int dist[N][N];
  12.  
  13. int main() {
  14.     cin >> n;
  15.    
  16.     cin >> f1 >> s1;
  17.     cin >> f2 >> s2;
  18.    
  19.     queue < pair <int, int> > q;
  20.     used[f1][s1] = 1;
  21.     q.push({f1, s1});
  22.  
  23.     while (!q.empty()) {
  24.         int x = q.front().first, y = q.front().second;
  25.         q.pop();
  26.         if (x - 1 >= 1 && y - 2 >= 1 && !used[x - 1][y - 2]) {
  27.             used[x - 1][y - 2] = 1;
  28.             dist[x - 1][y - 2] = dist[x][y] + 1;
  29.             q.push({x - 1, y - 2});
  30.         }
  31.         if (x - 1 >= 1 && y + 2 <= n && !used[x - 1][y + 2]) {
  32.             used[x - 1][y + 2] = 1;
  33.             dist[x - 1][y + 2] = dist[x][y] + 1;
  34.             q.push({x - 1, y + 2});
  35.         }
  36.         if (x + 1 <= n && y - 2 >= 1 && !used[x + 1][y - 2]) {
  37.             used[x + 1][y - 2] = 1;
  38.             dist[x + 1][y - 2] = dist[x][y] + 1;
  39.             q.push({x + 1, y - 2});
  40.         }
  41.         if (x + 1 <= n && y + 2 <= n && !used[x + 1][y + 2]) {
  42.             used[x + 1][y + 2] = 1;
  43.             dist[x + 1][y + 2] = dist[x][y] + 1;
  44.             q.push({x + 1, y + 2});
  45.         }
  46.         if (x - 2 >= 1 && y - 1 >= 1 && !used[x - 2][y - 1]) {
  47.             used[x - 2][y - 1] = 1;
  48.             dist[x - 2][y - 1] = dist[x][y] + 1;
  49.             q.push({x - 2, y - 1});
  50.         }
  51.         if (x - 2 >= 1 && y + 1 <= n && !used[x - 2][y + 1]) {
  52.             used[x - 2][y + 1] = 1;
  53.             dist[x - 2][y + 1] = dist[x][y] + 1;
  54.             q.push({x - 2, y + 1});
  55.         }
  56.         if (x + 2 <= n && y - 1 >= 1 && !used[x + 2][y - 1]) {
  57.             used[x + 2][y - 1] = 1;
  58.             dist[x + 2][y - 1] = dist[x][y] + 1;
  59.             q.push({x + 2, y - 1});
  60.         }
  61.         if (x + 2 <= n && y + 1 <= n && !used[x + 2][y + 1]) {
  62.             used[x + 2][y + 1] = 1;
  63.             dist[x + 2][y + 1] = dist[x][y] + 1;
  64.             q.push({x + 2, y + 1});
  65.         }  
  66.     }
  67.    
  68.     cout << dist[f2][s2] << endl;
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement