洛谷P1443 马的遍历

题目描述

有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步

输入输出格式

输入格式:

一行四个数据,棋盘的大小和马的坐标

输出格式:

一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

输入输出样例

输入样例#1: 复制

3 3 1 1

输出样例#1: 复制

0    3    2    
3    -1   1    
2    1    4    

水题一个,代码五分钟,bug两小时。。

话不多说,ACcode:

#include<bits/stdc++.h> 
using namespace std;
struct node{int x,y,t;};
bool vis[405][405];
int a[405][405];
queue<node> Q;
int n,m,sx,sy;
node temp;
void move(int x,int y,int t)
{
	if(x<1||y<1||x>n||y>m||vis[x][y]) return ;
	vis[x][y]=true;
	Q.push((node){.x=x,.y=y,.t=t});
}
void bread()
{
	vis[sx][sy]=true;
	Q.push((node){.x=sx,.y=sy,.t=0});
	while(!Q.empty())
	{
		temp=Q.front();  Q.pop();
		a[temp.x][temp.y]=temp.t;
		int x=temp.x, y=temp.y;
		move(x-2,y-1,temp.t+1);
		move(x-2,y+1,temp.t+1);
		move(x-1,y+2,temp.t+1);
		move(x+1,y+2,temp.t+1);
		move(x+2,y+1,temp.t+1);
		move(x+2,y-1,temp.t+1);
		move(x+1,y-2,temp.t+1);
		move(x-1,y-2,temp.t+1);
	}
}
int main()
{
	cin>>n>>m>>sx>>sy;
	memset(a,-1,sizeof(a));
	bread();
	for(int i=1;i<=n;i++,cout<<endl)
	for(int j=1;j<=m;j++)
	printf("%-5d",a[i][j]);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值