跳到正文

个人记录

DLMY Solution: T728724

Alexlulu约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年2月26日
更新
2026年2月28日
篇幅
约 5 分钟

版本

  1. v1当前

题目传送门:春节特别赛 DLMY棋

个人评价:下位黄

灵感来源:马的遍历

信息研修班原题,我们先从原题中找来 bfs 框架:

马的遍历
C++
#include <bits/stdc++.h>
using namespace std;

const int N = 410;
struct node { int x, y; };
int n, m, x, y, vis[N][N], dis[N][N], cht = 100007;
queue<node> q;

int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1};

void bfs()
{
	q.push({x, y});
	vis[x][y] = true;
	while (!q.empty())
	{
		int ox = q.front().x, oy = q.front().y;
		q.pop();
		for (int i = 0; i < 8; i++)
		{
			int nx = ox + dx[i], ny = oy + dy[i];
			if (nx > n || nx < 1 || ny > m || ny < 1 || vis[nx][ny]) continue;
			q.push({nx, ny});
			dis[nx][ny] = min(dis[nx][ny], dis[ox][oy] + 1);
			vis[nx][ny] = true;
			//printf("%d %d %d\n", nx, ny, dis[nx][ny]);
		}
	}
}

int main()
{
	scanf("%d%d%d%d", &n, &m, &x, &y);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			dis[i][j] = 1e9;
	dis[x][y] = 0;
	bfs();
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (i == x && j == y) printf("0 ");
			else if (dis[i][j] == 1e9) printf("-1 ");
			else printf("%d ", dis[i][j]);
		}
		printf("\n");
	}
	return 0;
}
// Solution by Alexlulu

好了,现在我们把 偏移量 进行修改,就可以轻松 AC\tt{\green{AC}} 啦!

AC 代码
C++
#include <bits/stdc++.h>
using namespace std;

const int N = 410;
struct node { int x, y; };
int n, m, x, y, vis[N][N], dis[N][N], cht = 100007;
queue<node> q;

int dx[] = {-2, -1, -1,  0, +1, +2, +2, +2};
int dy[] = {-2, -1, +2, -2, +1, -2,  0, +2};

void bfs()
{
	q.push({x, y});
	vis[x][y] = true;
	while (!q.empty())
	{
		int ox = q.front().x, oy = q.front().y;
		q.pop();
		for (int i = 0; i < 8; i++)
		{
			int nx = ox + dx[i], ny = oy + dy[i];
			if (nx > n || nx < 1 || ny > m || ny < 1 || vis[nx][ny]) continue;
			q.push({nx, ny});
			dis[nx][ny] = min(dis[nx][ny], dis[ox][oy] + 1);
			vis[nx][ny] = true;
			//printf("%d %d %d\n", nx, ny, dis[nx][ny]);
		}
	}
}

int main()
{
	scanf("%d%d%d%d", &n, &m, &x, &y);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			dis[i][j] = 1e9;
	dis[x][y] = 0;
	bfs();
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (i == x && j == y) printf("0 ");
			else if (dis[i][j] == 1e9) printf("-1 ");
			else printf("%d ", dis[i][j]);
		}
		printf("\n");
	}
	return 0;
}
// Solution by Alexlulu
原文