fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 2e2 + 5;
  12.  
  13. int dx[4] = {-1, -1, 1, 1};
  14. int dy[4] = {-1, 1, -1, 1};
  15.  
  16. int n, m, sx, sy, tx, ty;
  17. bool ban[N][N];
  18.  
  19. bool ok(int x, int y) {
  20. return (1 <= x && x <= n && 1 <= y && y <= n && !ban[x][y]);
  21. }
  22.  
  23. int dist[N][N];
  24.  
  25. void bfs(int sx, int sy) {
  26. for (int x = 1; x <= n; x++) {
  27. for (int y = 1; y <= n; y++) dist[x][y] = -1;
  28. }
  29.  
  30. queue<ii> q;
  31. dist[sx][sy] = 0;
  32. q.push({sx, sy});
  33.  
  34. while (!q.empty()) {
  35. ii u = q.front(); q.pop();
  36. int x = u.first, y = u.second;
  37.  
  38. for (int i = 0; i < 4; i++) {
  39. int nx = x, ny = y;
  40. while (ok(nx + dx[i], ny + dy[i])) {
  41. nx += dx[i], ny += dy[i];
  42. if (dist[nx][ny] == -1) {
  43. dist[nx][ny] = dist[x][y] + 1;
  44. q.push({nx, ny});
  45. }
  46. }
  47. }
  48. }
  49. }
  50.  
  51. int main() {
  52. ios::sync_with_stdio(false);
  53. cin.tie(nullptr);
  54. cin >> n >> m >> sx >> sy >> tx >> ty;
  55.  
  56. for (int i = 0; i < m; i++) {
  57. int x, y;
  58. cin >> x >> y;
  59. ban[x][y] = true;
  60. }
  61.  
  62. bfs(sx, sy);
  63.  
  64. cout << dist[tx][ty] << '\n';
  65. }
Success #stdin #stdout 0.01s 5284KB
stdin
8 3 7 2 1 4
5 4
3 4
4 7
stdout
3