蓝桥杯 迷宫(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;
}
相关推荐
小小龙学IT10 小时前
Boost.Interprocess 开源 C++ 进程间通信库深度解析
c++·开源
倒头就睡的小比特6 天前
算法竞赛C++常用的STL
c++·算法
weilx12346 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛6 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车6 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光6 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·6 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁6 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven6 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码6 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎