洛谷 P10491 [USACO09NOV] The Chivalrous Cow B C语言 bfs

题目:

https://www.luogu.com.cn/problem/P10491?contestId=217365

题目背景

农民 John 有很多牛,他想交易其中一头被 Don 称为 The Knight 的牛。这头牛有一个独一无二的超能力,在农场里像 Knight 一样地跳(就是我们熟悉的象棋中马的走法)。虽然这头神奇的牛不能跳到树上和石头上,但是它可以在牧场上随意跳,我们把牧场用一个 x,y 的坐标图来表示。

题目描述

这头神奇的牛像其它牛一样喜欢吃草,给你一张地图,上面标注了 The Knight 的开始位置,树、灌木、石头以及其它障碍的位置,除此之外还有一捆草。现在你的任务是,确定 The Knight 要想吃到草,至少需要跳多少次。The Knight 的位置用 K 来标记,障碍的位置用 * 来标记,草的位置用 H 来标记。

这里有一个地图的例子:

思路简单的bfs模版,方向数组改成八个就可以。

代码如下:

复制代码
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
int dx[8]={-1,-2,-2,-1,1,2,2,1};
int dy[8]={2,1,-1,-2,2,1,-1,-2};//马走8个方向
struct Node{
	int x;
	int y;
	int step;
};
bool stl[1005][1005];
char map[1005][1005];
int n,m;
int startx,starty;
int endx,endy;
int main() 
{
	queue <Node> q;
	cin >> m >> n;
	for(int i = 1 ; i <= n ; i++)
	{
		for(int j = 1 ; j <= m ; j++)
		{
			cin >> map[i][j];
			if(map[i][j] == 'K')
			{
				startx = i;
				starty = j;	
			}
			if(map[i][j] == 'H')
			{
				endx = i;
				endy = j;
			}
		}
	}
	
	Node start = {startx,starty,0};
	q.push(start);
	stl[startx][starty] = true;//标记已走过 
	
	while(!q.empty())
	{
		int x = q.front().x;//取出队首的三个数据 
		int y = q.front().y;
		int step = q.front().step;
		if(x == endx && y == endy)
		{
			cout << step << endl;
			break;
		}
		for(int k = 0 ; k < 8 ; k++)
		{
			int tx = x + dx[k];
			int ty = y + dy[k];
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && stl[tx][ty] == false && map[tx][ty] != '*' )
			{
				stl[tx][ty] = true;//标记已访问 
				Node newpos ={tx,ty,step+1};
				q.push(newpos);
			}
		 } 
		 q.pop();
	}



	return 0;
}
相关推荐
叩码以求索2 分钟前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana227 分钟前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
txzrxz37 分钟前
单调队列讲解
数据结构·c++·算法·单调队列
不会就选b1 小时前
算法日常・每日刷题--<快排>4
算法
Keven_111 小时前
算法札记:树状数组的用途
数据结构·算法
用户677437175812 小时前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法
cpp_25012 小时前
P1540 [NOIP 2010 提高组] 机器翻译
数据结构·c++·算法·队列·noip·洛谷题解
晚笙coding2 小时前
LeetCode 98:验证二叉搜索树 —— 从局部判断到全局范围约束的递归思想
算法·leetcode·职场和发展
学计算机的计算基2 小时前
回溯算法下篇:四道经典题讲透约束剪枝、原地标记、预计算与状态压缩
java·笔记·算法
霸道流氓气质3 小时前
SpringBoot中实现告警判定算法-位报警与模拟量阈值-技术详解
spring boot·算法·jquery