P1443 马的遍历

传送门

题目描述

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

输入格式

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

输出格式

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

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
const int mod = 1e9 + 7;
int n,m;
struct node{
	int x,y,step;
};
int a[8] = {1,2,2,1,-1,-2,-2,-1};
int b[8] = {2,1,-1,-2,-2,-1,1,2};
queue<node>q;
int ans[410][410];
int vis[410][410];
void bfs(int x,int y)
{
	node now;
	now.x = x;
	now.y = y;
	now.step = 0;
	q.push(now);
	while(!q.empty())
	{
		now = q.front();
		q.pop();
		ans[now.x][now.y] = now.step;
		vis[now.x][now.y] = -1;
		for(int i = 0; i < 8; i++)
		{
			node next;
			next.x = now.x + a[i];
			next.y = now.y + b[i];
			next.step = ans[now.x][now.y] + 1;
			if(next.x >= 1&& next.x <= m&& next.y >= 1&& next.y <= n&&vis[next.x][next.y] == 0)
			{
				vis[next.x][next.y] =  -1;
				q.push(next);
			}
		}
	}
}
int main()
{
	
	scanf("%d%d",&n,&m);
	int x,y;
	scanf("%d%d",&x,&y);
	memset(ans,-1,sizeof(ans));
	
	bfs(y,x);//下载了一个测试点才知道这题x和y是反着来的
	for(int j = 1; j <= n; j++)
	{
		for(int i = 1; i <= m; i++)
		{
			
				printf("%-5d",ans[i][j]);
			
		}
		printf("\n");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值