|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#define X first |
| 3 | +#define Y second |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +typedef long long ll; |
| 8 | +typedef long double ld; |
| 9 | +typedef pair<int, int> pi; |
| 10 | +typedef pair<pi, int> pii; |
| 11 | +typedef pair<pi, pi> pipi; |
| 12 | + |
| 13 | +const int MAX = 1e6 + 7; |
| 14 | +const int MOD = 1e9 + 7; |
| 15 | +const int INF = 1e9 + 7; |
| 16 | +int dx[] = { -1, 1, 0, 0 }; |
| 17 | +int dy[] = { 0, 0, -1, 1 }; |
| 18 | +int arr[1001][1001], dist[1001][1001][2]; |
| 19 | + |
| 20 | +int main (void) |
| 21 | +{ |
| 22 | + ios_base::sync_with_stdio (false); |
| 23 | + cin.tie (NULL); |
| 24 | + cout.tie (NULL); |
| 25 | + |
| 26 | + memset (dist, -1, sizeof (dist)); |
| 27 | + int N, M; |
| 28 | + cin >> N >> M; |
| 29 | + pi h, e; |
| 30 | + cin >> h.X >> h.Y; |
| 31 | + cin >> e.X >> e.Y; |
| 32 | + for (int i = 0; i < N; i++) { |
| 33 | + for (int j = 0; j < M; j++) cin >> arr[i][j]; |
| 34 | + } |
| 35 | + queue<pii> q; |
| 36 | + q.push ({h, 0}); |
| 37 | + dist[h.X][h.Y][0] = 0; |
| 38 | + while (!q.empty()) { |
| 39 | + auto cur = q.front(); |
| 40 | + q.pop(); |
| 41 | + if (cur.X.X == e.X && cur.X.Y == e.Y) { |
| 42 | + cout << dist[cur.X.X][cur.X.Y][cur.Y] << "\n"; |
| 43 | + return 0; |
| 44 | + } |
| 45 | + for (int i = 0; i < 4; i++) { |
| 46 | + int nx = cur.X.X + dx[i]; |
| 47 | + int ny = cur.X.Y + dy[i]; |
| 48 | + if (nx <= 0 || nx > N || ny <= 0 || ny > M) continue; |
| 49 | + int nc = cur.Y + arr[nx - 1][ny - 1]; |
| 50 | + if (nc >= 2) continue; |
| 51 | + if (dist[nx][ny][nc] != -1) continue; |
| 52 | + dist[nx][ny][nc] = dist[cur.X.X][cur.X.Y][cur.Y] + 1; |
| 53 | + q.push ({{nx, ny}, nc}); |
| 54 | + } |
| 55 | + } |
| 56 | + cout << "-1\n"; |
| 57 | + return 0; |
| 58 | +} |
0 commit comments