蓝桥杯 迷宫(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;
}
相关推荐
王老师青少年编程18 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮19 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
样例过了就是过了20 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
谭欣辰20 小时前
C++ 排列组合完整指南
开发语言·c++·算法
橙子也要努力变强21 小时前
信号捕捉底层机制-机理篇2
linux·服务器·c++
盐焗鹌鹑蛋21 小时前
【C++】stack和queue类
c++
郝学胜-神的一滴1 天前
罗德里格斯旋转公式(Rodrigues‘ Rotation Formula)完整推导
c++·unity·godot·图形渲染·three.js·unreal
lzh200409191 天前
深入理解进程:从PCB内核结构到写时拷贝的底层实战
linux·c++
aseity1 天前
跨平台项目中QString 与 非Qt 跨平台动态库在字符集上的一个实用的互操作约定.
c++·经验分享
CN-Dust1 天前
【C++】while语句例题专题
数据结构·c++·算法