蓝桥杯 迷宫(bfs)

0迷宫 - 蓝桥云课 (lanqiao.cn)


思路 :

最后一定要倒数输出路径,因为从前面输出你会找不到下一个到底是谁,bfs过程是找最小路径,最后输出是去找方向,但是此题作为一个填空题,我直接手写(开玩笑)


AC代码:

cpp 复制代码
#include<iostream>
#include<queue>
#include<utility>
#include<cstring>
#include<vector>

using namespace std;

typedef pair<int,int> PII;
char g[30][50];
int d[30][50],pre[40][60];
int ans = 0;
int dx[4] = {1,0,0,-1},dy[4] = {0,-1,1,0};
char dir[4] = { 'D','L','R','U' };                             

void bfs(int x,int y)
{
    queue<PII> q;
    q.push({x,y});
    memset(d,-1,sizeof d);
    d[0][0] = 0;
    while(q.size())
    {
    	auto t = q.front();
    	q.pop();
    	for(int i=0;i<4;i++)
    	{
    		int a = t.first + dx[i],b = t.second + dy[i];
    		if(a >= 0 && a < 30 && b >= 0 && b < 50 && g[a][b] == '0' && d[a][b] == -1)
    		{
    			d[a][b] = d[t.first][t.second] + 1;
    			pre[a][b] = i;
    			q.push({a,b});
			}
		}
	}
	return;
}

int main()
{
  // 请在此输入您的代码
  for(int i=0;i<30;i++)
  {
      for(int j=0;j<50;j++)
      {
          cin >>  g[i][j];
      }
  }
  bfs(0,0);
  int x = 29,y = 49;
  vector<int> v;
  while(x!=0 || y != 0)
  {
  	int temp = pre[x][y];
  	v.push_back(temp);
  	x -= dx[temp],y -= dy[temp];
  }
  for(int i=v.size()-1;i>=0;i--)  cout << dir[v[i]];
  return 0;
}
相关推荐
Tian_Hang31 分钟前
C++原型模式(Protype)
开发语言·c++·算法
FL16238631292 小时前
[cmake]基于C++使用纯opencv部署ppocrv5v6的onnx模型
开发语言·c++·opencv
玖玥拾2 小时前
C/C++ 数据结构(六)链表迭代器与底层
c语言·数据结构·c++·链表·stl库
牛油果子哥q2 小时前
AVL平衡树与红黑树深度精讲对比,平衡因子、四大旋转原理、着色规则、平衡策略、性能差异与面试手撕全解
数据结构·c++·面试
汉克老师2 小时前
GESP7级C++考试语法知识(二、指数函数(3、综合练习)
c++·算法·数学建模·指数函数·gesp7级·复利
C++ 老炮儿的技术栈2 小时前
Ubuntu root账号自动登陆
linux·运维·服务器·c语言·c++·ubuntu·visual studio
Irissgwe3 小时前
map/set/multimap/multiset 的底层逻辑与实现
数据结构·c++·算法·二叉树·stl·c·红黑树
思麟呀3 小时前
在C++基础上理解CSharp-5
开发语言·c++·c#
凡人叶枫3 小时前
Effective C++ 条款39:明智而审慎地使用 private 继承
java·数据库·c++·嵌入式开发
不想写代码的星星4 小时前
伪共享:逻辑无共享,物理打成狗
c++