马的遍历

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;
}
发布了63 篇原创文章 · 获赞 23 · 访问量 1382
展开阅读全文

没有更多推荐了,返回首页

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

分享到微信朋友圈

×

扫一扫,手机浏览