跳到正文

题解

题解:P10491 [USACO09NOV] The Chivalrous Cow B

xpg007约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年6月2日
篇幅
约 4 分钟
题目
P10491

版本

  1. v1当前

大家好呀!我是一只小苹果!今天我又来写题解了……

如果题解有不对的地方,欢迎大家吐槽指点。


这题有一个坑,那就是 mm 列 nn 行

这个地方输入时这样就可以了↓

C++
int n, m;
... //other codes
cin >> m >> n;

接下来是变量的部分,我们需要一个 mpmp 来记录地形,一个 visvis 来避免重复访问,一个 cntcnt 来记录步数, dxdx 和 dydy 来记录“马”的偏移量,一个 nodenode 来标记坐标,如下所示↓

C++
int n, m;
char mp[151][151];
bool vis[151][151];
int cnt[151][151];
int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
struct node{
	int x, y;
};

接着我们做一个 checkcheck 函数来判断坐标是否合法( xx 在 1 ~ mm 之间, mm 在 1 ~ mm ,未访问过,不是障碍),如下所示↓

C++
bool check(int x, int y){
	if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || mp[x][y] == '*')
		return false;
	else
		return true;
}

然后是主体 bfsbfs 部分(思路详见代码)↓

C++
void bfs(int x, int y){
	queue<node> q;
	q.push({x, y});
	vis[x][y] = true;
	while (!q.empty()){
		node f = q.front();
		q.pop();
		if (mp[f.x][f.y] == 'H'){
			cout << cnt[f.x][f.y];
			exit(0);
		}
		for (int i = 0; i < 8; i++){
			int tx = f.x + dx[i];
			int ty = f.y + dy[i];
			if (check(tx, ty)){
				q.push({tx, ty});
				vis[tx][ty] = true;
				cnt[tx][ty] = cnt[f.x][f.y] + 1;
			}
		}
	}
}

最后是完整代码↓

C++
#include <bits/stdc++.h>
using namespace std;
int n, m;
char mp[151][151];
bool vis[151][151];
int cnt[151][151];
int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
struct node{
	int x, y;
};
bool check(int x, int y){
	if (x < 1 || x > n || y < 1 || y > m || vis[x][y] || mp[x][y] == '*')
		return false;
	else
		return true;
}
void bfs(int x, int y){
	queue<node> q;
	q.push({x, y});
	vis[x][y] = true;
	while (!q.empty()){
		node f = q.front();
		q.pop();
		if (mp[f.x][f.y] == 'H'){
			cout << cnt[f.x][f.y];
			exit(0);
		}
		for (int i = 0; i < 8; i++){
			int tx = f.x + dx[i];
			int ty = f.y + dy[i];
			if (check(tx, ty)){
				q.push({tx, ty});
				vis[tx][ty] = true;
				cnt[tx][ty] = cnt[f.x][f.y] + 1;
			}
		}
	}
}
int main(){
	int sx, sy;
	cin >> m >> n;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++){
			cin >> mp[i][j];
			if (mp[i][j] == 'K')
				sx = i, sy = j;
		}
	bfs(sx, sy);
	return 0;
}

希望大家更注重解题思路,而非代码本身。

原文
存档评论2 条抓取于