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
| #include <bits/stdc++.h>
using namespace std;
struct Node { int x_, y_; Node(int x = 0, int y = 0) : x_(x), y_(y) {} };
queue<Node> q;
int N, M, ans[450][450], walk[8][2] = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}, {1, -2}, {2, -1}};
void bfs() { while (!q.empty()) { Node u = q.front(); q.pop(); int ux = u.x_, uy = u.y_; for (int i = 0; i < 8; ++i) { int x = ux + walk[i][0], y = uy + walk[i][1]; if (x < 1 || x > N || y < 1 || y > M || ans[x][y] != -1) continue; ans[x][y] = ans[ux][uy] + 1; q.emplace(x, y); } } }
int main() { int x, y; cin >> N >> M >> x >> y; memset(ans, -1, sizeof(ans)); q.emplace(x, y); ans[x][y] = 0; bfs(); for (int i = 1; i <= N; ++i, puts("")) for (int j = 1; j <= M; ++j) printf("%-5d", ans[i][j]); return 0; }
|