求条(为啥别人都是WA就我是TLE)
#include<bits/stdc++.h>
using namespace std;
const int N=2003;
int T,n,m,a[N][N],ans=1000000009;
char ch;
bool vis[N][N];
string anstr;
struct node{
int ai,aj,step;
string way;
};
void bfs(){
queue<node>q;
q.push((node){1,1,0,""});
while(q.size()){
node arr=q.front();
q.pop();
int x=arr.ai,y=arr.aj,as=arr.step;
if(vis[x][y])continue;
string str=arr.way;
if(x==n&&y==m){
ans=min(ans,as);
anstr=str;
}
vis[x][y]++;
if(x-1>=1&&a[x][y]!=a[x-1][y])q.push((node){x-1,y,as+1,str+"U"});
if(x+1<=n&&a[x][y]!=a[x+1][y])q.push((node){x+1,y,as+1,str+"D"});
if(y-1>=1&&a[x][y]!=a[x][y-1])q.push((node){x,y-1,as+1,str+"L"});
if(y+1<=m&&a[x][y]!=a[x][y+1])q.push((node){x,y+1,as+1,str+"R"});
//BFS奥义
}
}
int main(){
ios::sync_with_stdio(false);
cin>>T;
while(T--){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>ch;
if(ch=='0')a[i][j]=0;
else a[i][j]=1;
}
}
bfs();
if(ans==1000000009)cout<<-1<<endl;
else cout<<ans<<endl<<anstr<<endl;
ans=1000000009,anstr="";
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
vis[i][j]=0;
a[i][j]=0;
}
}
}
return 0;
}