# 马的遍历

Description

Format
Input

Output

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;
}


©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客