本地和洛谷在线IDE可行,提交RE #2
#include<bits/stdc++.h>
using namespace std;
int n, m, cnt, x[160010], y[160010], ans[410][410];
int xx[4] = {1, 1, -1, -1}, yy[4] = {1, -1, 1, -1};
bool f;
void add(int a, int b) {
x[++cnt] = a, y[cnt] = b;
}
bool check(int x, int y) {
return (x && y && x <= n && y <= n);
}
void bfs() {
queue<pair<int, int>> q;
q.push(make_pair(1, 1));
while (!q.empty()) {
pair<int, int> now = q.front();
q.pop();
int nx = now.first, ny = now.second;
for (int i = 1; i <= cnt; i++)
for (int j = 0; j < 4; j++) {
int dx = nx + xx[j] * x[i], dy = ny + yy[j] * y[i];
if (check(dx, dy) && ans[dx][dy] > ans[nx][ny] + 1) {
ans[dx][dy] = ans[nx][ny] + 1;
q.push(make_pair(dx, dy));
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) if (i * i + j * j == m) add(i, j);
memset(ans, 0x3f, sizeof(ans));
ans[1][1] = 0;
bfs();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cout << (ans[i][j] != 0x3f3f3f3f ? ans[i][j] : -1) << " ";
cout << "\n";
}
return 0;
}