传送门 | 难度 |
---|---|
https://www.luogu.com.cn/problem/P1443 | 普及/提高- |
分析
思路很傻瓜,不越界就行了。
但是输出很坑。这里需要使用%-5d来,满足输出。
-是左对齐打印,5是占5个字符位。
AC代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
int st[8][2] = { {-2,1} ,{-1,2}, {1,2}, {2,1}, {2,-1} ,{1,-2}, {-1,-2},{-2,-1} };
struct Node {
int x, y, c;
};
queue<Node> q;
int mp[405][405];
bool flag[405][405];
int n, m;
int sx, sy;
void bfs() {
q.push({ sx,sy ,1});
while (!q.empty()) {
Node node = q.front();
q.pop();
int xx = node.x; int yy = node.y; int cc = node.c;
if (xx<0 || xx>n - 1 || yy<0 || yy>m - 1)
continue;
if (flag[xx][yy]&&mp[xx][yy]<=cc)
continue;
flag[xx][yy] = true;
mp[xx][yy] = cc;
for (int i = 0; i < 8; ++i) {
q.push({ xx + st[i][0],yy + st[i][1],cc + 1 });
}
}
}
int main() {
cin >> n >> m;
cin >> sx >> sy;
sx--;
sy--;
bfs();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m - 1; ++j) {
if (mp[i][j] == 0)
printf("%-5d",-1);
else
printf("%-5d", mp[i][j] - 1);
}
if (mp[i][m-1] == 0)
printf("%-5d\n",-1);
else
printf("%-5d\n", mp[i][m-1] - 1);
}
return 0;
}