当前位置: 首页 > article >正文

蓝桥杯备考:BFS最短路径之kotori迷宫

这道题打眼一看又是找最短路径,所以我们还是用BFS

我们还是老样子,定义方向向量,然后用dfs遍历可以走的路径 把每个点的最短路径都标上号

最后我们再遍历存储最短路径的二维数组,我们把走到的出口全部计起来,然后找出路径最短的出口 打印

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 35;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
char a[N][N];
int n, m, x, y;
int path[N][N];
typedef pair<int, int> PII;
void bfs()
{
	queue<PII> q;
	q.push({ x,y });
	path[x][y] = 0;
	while (q.size())
	{
		auto t = q.front(); q.pop();
		int px = t.first; int py = t.second;
		for (int i = 0; i <= 3; i++)
		{
			int x = px + dx[i]; int y = py + dy[i];
			if (x > n || x<1 || y>m || y < 1) continue;
			if (path[x][y] != -1) continue;
			if (a[x][y] == '*') continue;
			path[x][y] = path[px][py] + 1;
			if (a[x][y] != 'e') q.push({ x,y });

		}
	}
}
int main()
{
	memset(path, -1, sizeof path);
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			cin >> a[i][j];
			if (a[i][j] == 'k')
			{
				x = i;
				y = j;
			}
		}
	}
	bfs();
	int cnt = 0, ret = 1e9;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (a[i][j] == 'e' && path[i][j] != -1)
			{
				ret = min(path[i][j], ret);
				cnt++;
			}
		}
	}
	if (cnt == 0) cout << -1 << endl;
	else
	{
		cout << cnt << " " << ret << endl;
	}

	return 0;
}


http://www.kler.cn/a/573704.html

相关文章:

  • go数组的声明和初始化
  • 黄昏时间户外街拍人像Lr调色教程,手机滤镜PS+Lightroom预设下载!
  • 面试问题(一)
  • Python数据可视化——Matplotlib的基本绘图:图形、轴、标签
  • GPU 英伟达GPU架构回顾
  • 【Git】Git 初识
  • 利用PyQt简单的实现一个机器人的关节JOG界面
  • 心率提取,FFT
  • (一)Java虚拟机——JVM的组成
  • 从0开始的操作系统手搓教程21:进程子系统的一个核心功能——简单的进程切换
  • Pytorch中的ebmedding到底怎么理解?
  • el-tree右键节点动态位置展示菜单;el-tree的节点图片动态根据节点属性color改变背景色;加遮罩层(opacity)
  • 蓝桥备赛(九)- 结构体和类
  • linux检查内存
  • springboot3.x下集成hsqldb数据库
  • wxWidgets GUI 跨平台 入门学习笔记
  • 问题描述:如何将ts文件转换mp4文件
  • 人工智能】数据挖掘与应用题库(401-500)
  • todo: 使用融云imserve做登录(android)
  • xshell中bashdb 调试器的详细使用方法