跳到正文

题解

题解:P12270 [蓝桥杯 2024 国 Python B] 马与象

Charged_Charge约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月9日
篇幅
约 3 分钟
获赞
2
题目
P12270

版本

  1. v1当前

洛谷 P12270

题目大意:

给定矩阵的边长 nn 和马的位置与象的位置,判断是否存在一方能吃掉宁外一方的局面,如果有,输出最小步数,如果没有,输出负一。

解题思路:

打两个广搜,搜索所有马与象能够到达的位置,并记录步数。最后,遍历所有马与象能够重合的位置,把每一个马与象到达这个地方的步数的和与当前的答案求较小值,最终输出答案。

AC 代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 55;
int n, ans = 0x3f3f3f3f;
int x, y, r, c;
int h[N][N];
int e[N][N];
int vh[N][N];
int ve[N][N];
int hx[8] = {-1, -2, 1, 2, -2, -1, 1, 2};
int hy[8] = {-2, -1, -2, -1, 1, 2, 2, 1};
int ex[4] = {-2, 2, -2, 2};
int ey[4] = {-2, -2, 2, 2};
struct node {
	int xx, yy;
	int s;
};

void bfs1(int l, int r) {
	queue<node> q;
	q.push({l, r, 0});
	vh[l][r] = 1;

	while (q.size()) {
		node p = q.front();
		q.pop();

		for (int i = 0; i < 8; i++) {
			int nx = p.xx + hx[i];
			int ny = p.yy + hy[i];

			if (nx < 0 || nx > n || ny < 0 || ny > n || vh[nx][ny]) {
				continue;
			}

			vh[nx][ny] = 1;
			h[nx][ny] = p.s + 1;
			q.push({nx, ny, h[nx][ny]});
		}
	}
}

void bfs2(int l, int r) {
	queue<node> q;
	q.push({l, r, 0});
	ve[l][r] = 1;

	while (q.size()) {
		node p = q.front();
		q.pop();

		for (int i = 0; i < 4; i++) {
			int nx = p.xx + ex[i];
			int ny = p.yy + ey[i];

			if (nx < 0 || nx > n || ny < 0 || ny > n || ve[nx][ny]) {
				continue;
			}

			ve[nx][ny] = 1;
			e[nx][ny] = p.s + 1;
			q.push({nx, ny, e[nx][ny]});
		}
	}
}

int main() {
	cin >> n;
	cin >> x >> y >> r >> c;
	memset(h, 0x3f, sizeof h);
	memset(e, 0x3f, sizeof e);
	h[x][y] = 0;
	e[r][c] = 0;
	bfs1(x, y);
	bfs2(r, c);

	for (int i = 0; i <= n; i++) {
		for (int j = 0; j <= n; j++) {
			ans = min(h[i][j] + e[i][j], ans);
		}
	}

	if (ans == 0x3f3f3f3f) {
		cout << -1;
	} else {
		cout << ans;
	}

	return 0;
}
原文