题目
题解思路
首先按字典序最小无非就是按这种顺序走,DFS中也是一样的。BFS本来可以更快解决迷宫类最短路的问题,但路径怎么处理呢,我想出了一种比较憨的办法,多用一个string变量(还是不太会用string然后看了别人的代码发现果然有人和我想的一样)记录每次的路径。 这里对结构体内置函数的处理真的巧妙,原来是让数值更方便的存进去。比如这样
struct node
{
int x,y,step;
string s;
node(int xx,int yy,int sttep,string ss)
{
x = xx;y = yy;s = ss;step =sttep;
}
};
queue <node > lu;
lu.push(node(0,0,0,"")); //像这样 真是巧妙
其他操作就和BFS相同了每次再多一个变量加上路径即可
if(mp[fx][fy] != '1'&&fx >= 0&&fx < 30&&fy >= 0&&fy < 50&&vis[fx][fy] == 0)
{
vis[fx][fy] = 1;
lu.push(node(fx,fy,t.step+1,t.s+xu[i]));
}
AC代码
#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
using namespace std;
struct node
{
int x,y,step;
string s;
node(int xx,int yy,int sttep,string ss)
{
x = xx;y = yy;s = ss;step =sttep;
}
};
char mp[33][55];
bool vis[33][55];
int dx[4] = {1,0,0,-1};
int dy[4] = {0,-1,1,0};
char xu[4] = {'D','L','R','U'};
int main()
{
queue <node > lu;
for(int i=0;i<30;i++)
cin>>mp[i];
vis[0][0] = 1;
lu.push(node(0,0,0,""));
while(!lu.empty())
{
node t=lu.front();
if( t.x == 29 && t.y == 49)
{
cout<<t.s<<"\n";
return 0;
}
for(int i = 0;i < 4; i++)
{
int fx = t.x + dx[i];
int fy = t.y + dy[i];
if(mp[fx][fy] != '1'&&fx >= 0&&fx < 30&&fy >= 0&&fy < 50&&vis[fx][fy] == 0)
{
vis[fx][fy] = 1;
lu.push(node(fx,fy,t.step+1,t.s+xu[i]));
}
}
lu.pop();
}
return 0;
}