【蓝桥杯】马的遍历

2023-12-13 07:37:49

马的遍历

题目描述

有一个 n × m n \times m n×m 的棋盘,在某个点 ( x , y ) (x, y) (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。

输入格式

输入只有一行四个整数,分别为 n , m , x , y n, m, x, y n,m,x,y

输出格式

一个 n × m n \times m n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 ? 1 -1 ?1)。

样例 #1

样例输入 #1

3 3 1 1

样例输出 #1

0    3    2    
3    -1   1    
2    1    4

提示

数据规模与约定

对于全部的测试点,保证 1 ≤ x ≤ n ≤ 400 1 \leq x \leq n \leq 400 1xn400 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1ym400

AC代码:

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 510;
int ans[N][N],n,m,x,y;
const int dx[8] = { -1,-2,-2,-1,1,2,2,1 };
const int dy[8] = { 2,1,-1,-2,2,1,-1,-2 };
typedef pair<int, int>PII;//开一个可以存两个int的变量,用于存坐标(x,y)
queue<PII> q;

void bfs()
{
	//队列非空
	while (!q.empty())
	{
		auto now = q.front();//记录下当前队列首元素
		q.pop();//将队列的首元素弹出
		int d = ans[now.first][now.second];
		for (int i = 0; i < 8; i++)
		{
			int ax = now.first + dx[i];
			int ay = now.second + dy[i];
			//如果跨过边界了或者当前位置访问过了,就直接continue不管
			if (ax<1 || ax>n || ay<1 || ay>m || ans[ax][ay] != -1)
				continue;
			ans[ax][ay] = d + 1;//在上一次的距离加上1
			q.push({ ax,ay });//继续入队列
		}
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			printf("%-5d", ans[i][j]);
		}
		puts("");
	}
}

int main(void)
{
	cin >> n >> m >> x >> y;
	memset(ans, -1,sizeof ans);//没有访问就标记为-1
	ans[x][y] = 0;//从[x,y]走的,当前格子步数就是0
	q.push({ x,y });//将[x,y]坐标加入到队列当中
	bfs();
	return 0;
}

文章来源:https://blog.csdn.net/2301_79516932/article/details/134793942
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。