1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <algorithm> #include <cstring> #include <iostream> #include <queue> #define x first #define y second using namespace std;
typedef pair<int, int> PII; const int N = 110; int n, m;
int map[N][N]; int idx[N][N];
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0};
void bfs(int x1, int y1, int x2, int y2) { memset(idx, -1, sizeof idx); queue<PII> q; q.push({x1, y1}); idx[x1][y1] = 0; while (!q.empty()) { auto t = q.front(); for (int i = 0; i < 4; i++) { int x = t.x + dx[i], y = t.y + dy[i]; if (x < 1 && y < 1 && x > m && y > n) continue; if (map[x][y] == 0) continue; if (idx[x][y] != -1) continue; idx[x][y] = idx[t.x][t.y] + 1; q.push({x, y}); if (x == x2 && y == y2) return; } q.pop(); } return; }
int main() { scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &map[i][j]);
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
bfs(x1, y1, x2, y2);
if (idx[x2][y2] != -1) printf("%d\n", idx[x2][y2]); else printf("-1\n");
return 0; }
|