题目链接:
https://www.luogu.com.cn/problem/P1443
思路:
一道广度优先搜索求最短路的裸题
注意数字左对齐宽n
格用printf
输出格式为%-nd
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 404;
int n, m, x, y;
int mat[maxn][maxn];
queue<pair<int, int> > que;
int d;
inline void check(int a, int b) {
if(a >= 1 && b >= 1 && a <= n && b <= m && mat[a][b] == -1) {
mat[a][b] = d;
que.push(make_pair(a, b));
}
}
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
scanf("%d %d %d %d", &n, &m, &x, &y);
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
mat[i][j] = -1;
}
}
mat[x][y] = 0;
que.push(make_pair(x, y));
while(!que.empty()) {
pair<int, int> now = que.front(); que.pop();
int a = now.first, b = now.second;
d = mat[a][b] + 1;
check(a - 2, b - 1);
check(a - 2, b + 1);
check(a - 1, b - 2);
check(a - 1, b + 2);
check(a + 1, b - 2);
check(a + 1, b + 2);
check(a + 2, b - 1);
check(a + 2, b + 1);
}
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
printf("%-5d", mat[i][j]);
}
putchar('\n');
}
return 0;
}