思路:
广搜,记录路径,反向输出
#include <iostream>
#include <queue>
#include <stdio.h>
#include <algorithm>
using namespace std;
int mp[505][505];
char path[505][505];
int vis[505][505];
struct node
{
int step,x,y;
};
int n,m,ans;
queue <node>s;
int judge(int x,int y,int step)
{
if(x>n||x<1||y>m||y<1||mp[x][y])
{
return 0;
}
if(vis[ x][ y]!=0&&vis[ x][ y]<= step)
return 0;
vis[x][y]=step;
node t;
t.x=x,t.y=y,t.step=step;
s.push(t);
return 1;
}
void bfs()
{
while(!s.empty())
{
node t=s.front();
s.pop();
if(t.step>=ans)
{
break;
}
if(t.x==n&&t.y==m)
{
ans=t.step;
continue;
}
vis[t.x][t.y]=t.step;
if(judge(t.x+1,t.y,t.step+1))
{
path[t.x+1][t.y]='D';
}
if(judge(t.x,t.y-1,t.step+1))
{
path[t.x][t.y-1]='L';
}
if(judge(t.x,t.y+1,t.step+1))
{
path[t.x][t.y+1]='R';
}
if(judge(t.x-1,t.y,t.step+1))
{
path[t.x-1][t.y]='U';
}
}
}
char res[250005];
void printf_path()
{
int stx,sty;
stx=n,sty=m;
while(stx!=1||sty!=1)
{
if(path[stx][sty]=='D')
res[--ans]='D',stx--;
else if(path[stx][sty]=='L')
res[--ans]='L',sty++;
else if(path[stx][sty]=='R')
res[--ans]='R',sty--;
else if(path[stx][sty]=='U')
res[--ans]='U',stx++;
}
cout<<res<<endl;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%1d",&mp[i][j]);
}
}
node t;
ans=0x3f3f3f3f;
t.x=1,t.y=1,t.step=0;
s.push(t);
bfs();
cout<<ans<<endl;
printf_path();
}