luogu P1443 马的遍历

https://www.luogu.org/problem/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

代码

/*
注意:
	是n行m列  
*/
#include<algorithm>
#include<string.h>
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;

const int maxn = 410;
int d[2][8] = { {1, 1,2, 2,-1,-1,-2,-2},
			{ 2,-2,1,-1, 2,-2, 1,-1} };
int n, m;
int x, y;
int g[maxn][maxn];
int visited[maxn][maxn];

struct node
{
	int a, b;
	node(int x, int y) :a(x), b(y) {}
};

int borderline(int x, int y)
{
	return (x > 0 && x <= n && y > 0 && y <= m);
}

void bfs()
{
	queue <node> q;
	q.push(node(x, y));

	while (!q.empty())
	{
		node t = q.front(); q.pop();

		for (int i = 0; i < 8; i++)
		{
			int tx = t.a + d[0][i];
			int ty = t.b + d[1][i];
			if (borderline(tx, ty) && !visited[tx][ty])
			{
				visited[tx][ty] = 1;
				g[tx][ty] = g[t.a][t.b] + 1;
				q.push(node(tx, ty));
			}
		}
	}
}

int main()
{
	scanf("%d%d%d%d", &n, &m, &x, &y);
	memset(g, -1, sizeof g);
	g[x][y] = 0;
	bfs();
	g[x][y] = 0;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
			printf("%-5d", g[i][j]);
		puts("");
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值