马的遍历

该博客探讨如何在n*m的棋盘上计算马从特定起点到达任意位置的最少步数。输入包括棋盘尺寸和马的初始坐标,输出为一个矩阵,显示每个位置所需的最少步数(无法到达的位置标记为-1)。题目来源于洛谷,限制时间为1秒,内存限制为1024KiB。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值