Description
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
Format
Input
一行四个数据,棋盘的大小和马的坐标
Output
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
Sample 1
Input
3 3 1 1
Output
0 3 2
3 -1 1
2 1 4
Limitation
1s, 1024KiB for each test case.
Source
洛谷
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN = 500;
int nBoard, mBoard;
int xStart, yStart;
int Board[MAXN][MAXN];
struct pos {
int x;
int y;
int s;
};
queue<pos> q;
int dx[8] = { -2,-1,1,2,2,1,-1,-2 };
int dy[8] = { 1,2,2,1,-1,-2,-2,-1 };
int main() {
scanf("%d%d%d%d", &nBoard, &mBoard, &xStart, &yStart);
for (int i = 1; i <= nBoard; i++) {
for (int j = 1; j <= mBoard; j++) {
Board[i][j] = -1;
}
}
Board[xStart][yStart] = 0;
pos tmp;
tmp.x = xStart;
tmp.y = yStart;
tmp.s = 0;
q.push(tmp);
while (!q.empty()) {
pos now = q.front();
q.pop();
int x = now.x;
int y = now.y;
int s = now.s;
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<1 || nx>nBoard || ny<1 || ny>mBoard || Board[nx][ny] != -1) {
continue;
}
now.x = nx;
now.y = ny;
now.s = s + 1;
q.push(now);
Board[nx][ny] = s + 1;
}
}
for (int i = 1; i <= nBoard; i++) {
for (int j = 1; j <= mBoard; j++) {
printf("%-5d", Board[i][j]);
}
printf("\n");
}
return 0;
}