搜索—迷宫

直达原题

分析

本题最短路径就是用bfs进行搜索,但还要涉及到打印操作;我们可以每搜索一个最短路径的点就把他记录下来,也可以只记录他的前驱节点。

代码实现

#include <bits/stdc++.h>
using namespace std;
char mp[31][51];
int dir[4][2] = {{1,0},{0,-1},{0,1},{-1,0}};//注意要按字典序,所以这个方向位置是固定的
char pri[4] = {'D','L','R','U'};
bool vis[30][50];
struct node
{
	int i,j;
	char val;
	string path;
};

void bfs(){
	queue<node>q;
	node fir;
	fir.i = 0,fir.j = 0,fir.val = mp[0][0];
	fir.path = "";
	q.push(fir);
	vis[fir.i][fir.j]  = 1;
	while(!q.empty()){
		node now = q.front();
		q.pop();
		if(now.i == 29&&now.j == 49)
			{
				cout<<now.path<<endl;
				return;
			}
		for(int i = 0;i < 4;i ++){
			node next;
			next.i = now.i+dir[i][0];
			next.j = now.j+dir[i][1];
			next.val = mp[next.i][next.j];
			if(next.i>=0&&next.i<30&&next.j>=0&&next.j<50&&!vis[next.i][next.j]&&next.val == '0')
			{
				vis[next.i][next.j] = 1;
				next.path = now.path + pri[i];
				q.push(next);
			}
		}
	}
}
int main(){
	for(int i = 0;i<30;i++)cin>>mp[i];
	bfs();
	return 0;
}
posted @ 2023-08-22 03:28  LongDz  阅读(23)  评论(0)    收藏  举报