Luogu P1443 The Traversal of Horses - Guangsou

topic description

There is an n×m chessboard, and there is a horse at a certain point (x, y). You are required to calculate the minimum number of steps the horse needs to take to reach any point on the chessboard.

input format

The input is only one line of four integers, namely n, m, x, y.

output format

An n×m matrix, representing the minimum number of steps the horse has to take to reach a certain point (if it cannot reach it, output −1).

Input and output samples

enter 

3 3 1 1

output 

0    3    2    
3    -1   1    
2    1    4    

Instructions/Tips

Data size and conventions

For all test points, it is guaranteed that 1≤x≤n≤400, 1≤y≤m≤400.

 

#include<iostream>
#include<iomanip>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;

int n, m, sx, sy;
int mp[410][410];
int xx[] = { 2,2, 1, 1,-1,-1,-2,-2 };
int yy[] = { 1,-1,2,-2, 2,-2,1,-1 };
struct node
{
	int x, y, s;
};
int main()
{
	cin >> n >> m >> sx >> sy;
	memset(mp, -1, sizeof(mp));
	queue<node>q;
	node t;
	t.x = sx; t.y = sy; t.s = 0;
	q.push(node{ sx,sy,0 });
	mp[sx][sy] = 0;
	while (!q.empty())
	{
		for (int i = 0; i < 8; i++)
		{
			int dx = xx[i] + q.front().x;
			int dy = yy[i] + q.front().y;
			if (dx >= 1 && dx <= n && dy >= 1 && dy <= m && mp[dx][dy] == -1)
			{
				q.push(node { dx, dy, q.front().s + 1 });
				mp[dx][dy] = q.front().s + 1;
			}
		}
		q.pop();
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			printf("-5%d", mp[i][j]);
		}
		cout << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_73648729/article/details/129351941