呜呜呜 这题做了我好久好久,一开始拿DFS写了半天,写是写出来了,但是实在是太大了,笑死,根本搜不出来,后来又在网上看各种各样的题解,总算给我给搞出来了,因为BFS本身没有DFS掌握的牢固,所以有些不太敢拿BFS写,晚上要把BFS的基本功加强一下,加油加油!
#include<queue>
#include<iostream>
using namespace std;
int n=30,m=50;
string mp[35];
bool vis[35][55];
int dir[4][2]={{1,0},{0,-1},{0,1},{-1,0}};
struct node
{
int x,y,step;
string str;
node(int _x,int _y,int _step,string _str)
{
x=_x;
y=_y;
step=_step;
str=_str;
}
};
int main()
{
for(int i=0;i<n;i++)
{
cin>>mp[i];
}
string s="";
queue<node> q;
q.push(node(0,0,0,""));
vis[0][0]=true;
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.x==n-1&&now.y==m-1)
{
cout<<now.step<<endl;
cout<<now.str<<endl;
}
for(int i=0;i<4;i++)
{
int tx=now.x+dir[i][0];
int ty=now.y+dir[i][1];
if(tx<0||tx>=n||ty<0||ty>=m||vis[tx][ty]||mp[tx][ty]=='1')
{
continue;
}
if(i==0)s="D";
else if(i==1)s="L";
else if(i==2)s="R";
else s="U";
vis[tx][ty]=true;
q.push(node(tx,ty,now.step+1,now.str+s));
}
}
}