#include <bits/stdc++.h>
using namespace std;
char mp[30][50]; //地图
bool vis[30][50]; //是否被走过
int dir[4][2] = { {1,0}, {0,1}, {-1,0}, {0,-1} }; // 按照数组方向:下,右,上,左
char dirc[4] = {'D','R','U','L'};
int n, m; //迷宫的行和列
//对于dfs 和 bfs 来说 数组的基本信息最好放在全局变量
struct node //bfs 必带结构体
{
int x; // 横坐标
int y; // 纵坐标
int step; //步数
string str; //路径
node(int xx, int yy, int pp, string s)
{
x = xx; y = yy; step = pp; str = s;
}
};
queue <node> Q; //***先创建结构体 ,再 queue <结构名> Q 的格式(Q代表队列名)
bool check(int x, int y)//判断是否越界、是否走过、是否是障碍物
{
if(x<0 || x>=n || y<0 || y>=m || vis[x][y] || mp[x][y] == '1')
return false;
return true;
}
void bfs (int x, int y){
Q.push(node(x,y,0,"")); //bfs 一进来我们就需要将初始位置 入队列、标记已走过。
vis[x][y] = true; // 标准 Q.push(结构名(属性,属性···))
while(!Q.empty()){
node now = Q.front(); //每层的while 都会 Q.front 来查看队首 是否满足break条件
if(now.x == n-1 && now.y == m-1){
cout<<now.str<<endl;
cout<<now.step<<endl;
break;
}
Q.pop(); //如果没到终点,舍弃队首、出队列
for(int i=0; i<4; i++){
int nx = now.x + dir[i][0];
int ny = now.y + dir[i][1];
if(check(nx,ny)){
Q.push(node(nx, ny, now.step+1, now.str+dirc[i])); //步数和路程都是不断叠加起来的,每一个结构体包含之前所有的步数和路径 + 当前步数(1)和对应步伐
vis[nx][ny] = true;
}
}
}
}
int main(){
cin>>n>>m;
for(int i=0; i<n; i++) //对于大数据整数输入,一层循环即可,n代表有多少排
cin>>mp[i]; // 这里其实每次输入一排的数据
bfs(0,0);
return 0;
}
蓝桥杯---bfs
最新推荐文章于 2024-03-11 22:12:55 发布