【洛谷】P1449 马的遍历 (广度优先搜索)

马的遍历

题目描述

有一个 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

思路

与迷宫问题不同的地方在于x,y的增量是按照马的规则进行,马能够跳过去的点位需要的步数是它目前所在点位已跳步数加1

代码

#include<bits/stdc++.h>
using namespace std;
int x,y,n,m;
int chess[401][401];
int X[8]={1,2,2,1,-1,-2,-2,-1};
int Y[8]={2,1,-1,-2,-2,-1,1,2};
struct node{
	int xx,yy,steps=0;
}Node;
bool judge(int x,int y)
{
	if(x>n||x<1||y>m||y<1)
	return false;
	return true;
}
void bfs(int chess[401][401])
{
	queue<node> Q;
	Node.xx=x;   Node.yy=y;
	chess[Node.xx][Node.yy]=Node.steps;
	Q.push(Node);
	while(!Q.empty())
	{
		node top = Q.front();
		Q.pop();
		top.steps++;
		for(int i=0;i<8;i++)
		{
			int newx=top.xx+X[i];
			int newy=top.yy+Y[i];
			if(judge(newx,newy)&&chess[newx][newy]==-1)
			{
				chess[newx][newy]=top.steps;
				Node.xx=newx; Node.yy=newy;
				Node.steps=top.steps;
				Q.push(Node);
			}	
		}		
	}
}
int main()
{
	cin>>n>>m>>x>>y;
	memset(chess,-1,sizeof(chess));
	bfs(chess);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cout<<chess[i][j]<<"    ";
		}
		cout<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值